Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finishing stream with iterator vs collect?

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).

like image 632
dhblah Avatar asked Nov 29 '22 14:11

dhblah


1 Answers

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).

like image 174
Holger Avatar answered Dec 22 '22 11:12

Holger