Sorting a list with stream.sorted() in Java

前端 未结 6 1021
无人及你
无人及你 2020-11-27 05:32

I\'m interested in sorting a list from a stream. This is the code I\'m using:

list.stream()
    .sorted((o1, o2)->o1.getItem().getValue().compareTo(o2.get         


        
6条回答
  •  半阙折子戏
    2020-11-27 06:10

    This is not like Collections.sort() where the parameter reference gets sorted. In this case you just get a sorted stream that you need to collect and assign to another variable eventually:

    List result = list.stream().sorted((o1, o2)->o1.getItem().getValue().
                                       compareTo(o2.getItem().getValue())).
                                       collect(Collectors.toList());
    

    You've just missed to assign the result

提交回复
热议问题