Stream characteristics for streams generated for SortedMap may not be displayed in SORTED if they are created using a custom Comparator

Mastering Lambdas by Maurice Naphthalene, Ch6 - Flow Efficiency.

There is an explanation of the various flow characteristics at different stages of execution (intermediate and final). For instance,

Stream.of(8,3,5,6,7,4)//ORDERED, SIZED .filer(i->i%2==0) // ORDERED .sorted() // ORDERED, SORTED .distinct() // DISTINCT, ORDERED, SORTED .map(i->i+1) // ORDERED .unordered(); //none 

What baffled me was the explanation of the SORTED characteristics:

"Elements of a stream can be sorted in other orders if the Comparator was defined and used for this purpose, but such streams do not have the SORTED characteristic.

Why, if a specialized comparator is provided for implementing the Sorted Data Structure (SortedMap in the above case), the structure will not consider creating streams with the SORTED characteristic?

+5
source share
1 answer

Flown is absolutely right in his comment. SORTED is only reported for the natural order, and this has been discussed previously. At first, it is even internally used as a flag called: isNaturalSort :

 /** * Sort using natural order of {@literal <T>} which must be * {@code Comparable}. */ OfRef(AbstractPipeline<?, T, ?> upstream) { super(upstream, StreamShape.REFERENCE, StreamOpFlag.IS_ORDERED | StreamOpFlag.IS_SORTED); this.isNaturalSort = true; 

The same flag isNaturalSort set to false when used through sorted(CustomComparator) .

These are internal details, and it seems that the jdk developers did not find useful for its implementation as such - perhaps it did not matter what could be really useful. But that can change ...

There is at least one drawback. Imagine a class like this:

 static class User implements Comparable<User> { private final int id; public User(int id) { super(); this.id = id; } public int getId() { return id; } @Override public int compareTo(User usr) { return 42; // don't do this } } 

And some stream operations:

 Stream<User> byId = Stream.of(new User(12), new User(10)) .sorted(Comparator.comparing(User::getId)); System.out.println(byId.spliterator().hasCharacteristics(Spliterator.SORTED)); Stream<User> natural = Stream.of(new User(12), new User(10)) .sorted(Comparator.naturalOrder()); System.out.println(natural.spliterator().hasCharacteristics(Spliterator.SORTED)); Stream<User> plain = Stream.of(new User(12), new User(10)).sorted(); System.out.println(plain.spliterator().hasCharacteristics(Spliterator.SORTED)); 

The first two reports are false , but the last reports true ; which is at least strange.

+6
source

Source: https://habr.com/ru/post/1268750/


All Articles