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.
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.
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.
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.
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.
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With