Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does partitioningBy preserve order of elements in the original list?

I have ordered list of LocalDateTime and I need to split it on midnight of specific date. The order of elements in two new lists should not be changed.

List<LocalDateTime> l = Arrays.asList(LocalDateTime.of(2017,10,24,7,0,0),LocalDateTime.of(2017,10,24,8,0,0),LocalDateTime.of(2017,10,25,7,0,0),LocalDateTime.of(2017,10,25,9,0,0));

Does Collectors.partitioningBy provide a guarantee that the order will be preserved?

l.stream().collect(Collectors.partitioningBy(t-> t.isAfter(LocalDateTime.of(2017,10,25,0,0,0))))

Output:

{false=[2017-10-24T07:00, 2017-10-24T08:00], true=[2017-10-25T07:00, 2017-10-25T09:00]}
like image 936
leon01 Avatar asked Oct 18 '25 09:10

leon01


1 Answers

The documentation of the built-in collectors explicitly mentions when a Collector is an unordered collector, e.g. for toSet() or groupingByConcurrent(…). All collectors not specified to be unordered will preserve the encounter order, if the stream is ordered and they don’t have a downstream collector that is itself unordered.

partitioningBy(predicate) is equivalent to partitioningBy(predicate, toList()) and hence, will maintain the encounter order.

A counter-example would be partitioningBy(predicate, toSet()) which does not preserve any order and likewise, a stream that itself is unordered, e.g. hashSet.stream() .collect(partitioningBy(predicate)), does not make any guarantees about the result order.

like image 117
Holger Avatar answered Oct 20 '25 22:10

Holger