Sorting a list with stream.sorted() in Java

前端 未结 6 1029
无人及你
无人及你 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:15

    It seems to be working fine:

    List list = Arrays.asList(new BigDecimal("24.455"), new BigDecimal("23.455"), new BigDecimal("28.455"), new BigDecimal("20.455"));
    System.out.println("Unsorted list: " + list);
    final List sortedList = list.stream().sorted((o1, o2) -> o1.compareTo(o2)).collect(Collectors.toList());
    System.out.println("Sorted list: " + sortedList);
    

    Example Input/Output

    Unsorted list: [24.455, 23.455, 28.455, 20.455]
    Sorted list: [20.455, 23.455, 24.455, 28.455]
    

    Are you sure you are not verifying list instead of sortedList [in above example] i.e. you are storing the result of stream() in a new List object and verifying that object?

提交回复
热议问题