Why is there no min () version without parameters in the Java 8 Stream interface?

Interface

java.util.stream.Streamhas two versions of the method sorted- sorted()which sorts the elements in natural order and sorted(Comparator). Why min()wasn’t the method introduced in an interface Streamthat would return a minimal element from a natural point of view?

+6
source share
4 answers

I think that min () only allows a signature that the Comparator accepts, because Stream can be of any type, even the type you created. In this case, it would be impossible to rely on the natural order, since the class you created cannot have a natural order until you specify it.

Stream, , IntStream, , min() . , . :

public static void main (String... args){
        IntStream s=IntStream.of(1,2,3,4,5,6,7,8,9,10);
        System.out.println(s.min().getAsInt());
    }
+3

Comparator.naturalOrder . ( ) , Comparator.

T Comparable.

+3

, API. , " ", " CharStream", , , .

min :

someList.stream().min(Comparator.naturalOrder());

.

, API .

+3

, min, max sorted Stream, , , Java , .

, , sorted()?

, , . Generics , Comparator . , , , . , , . , , , .

. List.sort(Comparator), Java 8, null " ", , , , , .

, , . Stream.sorted(Comparator) - , null. Comparator.naturalOrder() sorted() . , null sorted() - , Stream , , Comparator.naturalOrder().

As a rule, the safety of comparator types is low. For example. Collections.reverseOrder()returns a comparator of an arbitrary type without requiring a comparable type. Therefore, instead, min()you can use max(Collections.reverseOrder())to query for a minimum regardless of the formal type of threads. Or use Collections.reverseOrder(Collections.reverseOrder())to get the equivalent Comparator.naturalOrder()for an arbitrary type. Similarly, it Collatorimplements Comparator<Object>, for some reason, despite the fact that it can only compare Strings.

+3
source

All Articles