Finding Max with Lambda Expression in Java

前端 未结 3 1560
孤城傲影
孤城傲影 2020-12-17 15:23

This is my code

    List ints = Stream.of(1,2,4,3,5).collect(Collectors.toList());
    Integer maxInt = ints.stream()
                                 


        
3条回答
  •  长情又很酷
    2020-12-17 15:33

    This function (note -> is for closures and not to be confused with => which is for comparison)

    i -> i
    

    just means you need to compare the entire object as it is. i.e. if I have an i you need to compare i

    A less trivial example might be

    max(Comparator.comparing(i -> -i))
    

    which will give you the minimum or

    max(Comparator.comparing(i -> Math.abs(100-i))
    

    gives you a value which is farthest from 100.

    max(Comparator.comparing(i -> i.toString()))
    

    which will give you the maximum comparing as a String i.e. "9" > "10" as a string.

提交回复
热议问题