Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I iterate over a stream in Java using for? [duplicate]

I have this code:

List<String> strings = Arrays.asList("a", "b", "cc"); for (String s : strings) {     if (s.length() == 2)         System.out.println(s); } 

I want to write it using a filter and a lambda:

for (String s : strings.stream().filter(s->s.length() == 2)) {     System.out.println(s); } 

I get Can only iterate over an array or an instance of java.lang.Iterable.

I try:

for (String s : strings.stream().filter(s->s.length() == 2).iterator()) {     System.out.println(s); } 

And I get the same error. Is this even possible? I would really prefer not to do stream.forEach() and pass a consumer.

Edit: it's important to me not to copy the elements.

like image 552
ytoledano Avatar asked Jun 25 '15 07:06

ytoledano


People also ask

What is the function used to duplicate a stream?

CopyTo(Stream) Reads the bytes from the current stream and writes them to another stream. Both streams positions are advanced by the number of bytes copied.

How does stream detect duplicate values in a list?

Get the stream of elements in which the duplicates are to be found. For each element in the stream, count the frequency of each element, using Collections. frequency() method. Then for each element in the collection list, if the frequency of any element is more than one, then this element is a duplicate element.

Which method is used to iterate over stream in java?

You can use stream() method of the List interface which gives a stream to iterate using forEach method. In forEach method, we can use the lambda expression to iterate over all elements.

How do I find duplicate values in java 8?

In Java 8 Stream, filter with Set. Add() is the fastest algorithm to find duplicate elements, because it loops only one time. Set<T> items = new HashSet<>(); return list.


1 Answers

You need an iterable to be able to use a for-each loop, for example a collection or an array:

for (String s : strings.stream().filter(s->s.length() == 2).toArray(String[]::new)) { 

Alternatively, you could completely get rid of the for loop:

strings.stream().filter(s->s.length() == 2).forEach(System.out::println); 

You mention you don't want to refactor your for loop but you could extract its body in another method:

strings.stream().filter(s->s.length() == 2).forEach(this::process);  private void process(String s) {   //body of the for loop } 
like image 80
assylias Avatar answered Oct 08 '22 02:10

assylias