Say, I want to filter a list and return the filtered list, but iterator would suffice too. Which of the following options is preferable and why? Stream.iterator()
or Stream.collect(ListCollector)
.
There is a fundamental difference between Stream.iterator()
and .collect(Collectors.toList()) .iterator()
. The latter will process all items of the stream in order to store them into a collection. In contrast, Stream.iterator()
will just return a wrapper around the Stream
’s Spliterator
which will process all items lazily like all other stream operations do.
E.g. when you write
Iterator<String> it=IntStream.range(0, 100).mapToObj(i->{
System.out.println("processing "+i);
return String.valueOf(i);
}).iterator();
if(it.hasNext()) System.out.println("first: "+it.next());
if(it.hasNext()) System.out.println("second: "+it.next());
return;// I don’t care about the remaining values
it will print:
processing 0
first: 0
processing 1
second: 1
while
Iterator<String> it=IntStream.range(0, 100).mapToObj(i->{
System.out.println("processing "+i);
return String.valueOf(i);
}).collect(Collectors.toList()).iterator();
if(it.hasNext()) System.out.println("first: "+it.next());
if(it.hasNext()) System.out.println("second: "+it.next());
return;// I don’t care about the remaining values
will print
processing 0
processing 1
processing 2
processing 3
processing 4
processing 5
processing 6
processing 7
processing 8
processing 9
processing 10
…
processing 90
processing 91
processing 92
processing 93
processing 94
processing 95
processing 96
processing 97
processing 98
processing 99
first: 0
second: 1
That said, if all you need is an Iterator
you should not enforce collecting the values before requesting it, unless you have a strong reason to do so (e.g., if the source is a file, you might want to finish the operation before returning the iterator).
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