Why Java 8 Stream interface does not have min() no-parameter version?

前端 未结 4 1692
难免孤独
难免孤独 2020-12-31 06:55

java.util.stream.Stream interface has two versions of sorted method – sorted() which sorts elements in natural order and sorted(

4条回答
  •  情深已故
    2020-12-31 07:40

    I think min() only allows the signature that accepts a Comparator because the Stream could be of any type, even a type created by you. In such case it would be impossible to rely on a natural order, as the class you've created, can't have a natural order until you specify it.

    If, insteam of the class Stream you use, IntStream, you'll see that a min() method with no arguments is defined. This does what you want. It is the following:

    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());
        }
    

提交回复
热议问题