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]}
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.
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