使用Java中的stream.sorted()对列表进行排序

我有兴趣从流中排序列表。 这是我正在使用的代码:

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

我错过了什么吗? 该列表没有排序。

它应该根据具有最低值的项目对列表进行排序。

 for (int i = 0; i < list.size(); i++) { System.out.println("list " + (i+1)); print(list, i); } 

和打印方法:

 public static void print(List list, int i) { System.out.println(list.get(i).getItem().getValue()); } 

这与参数引用排序的Collections.sort() 。 在这种情况下,您只需获取需要收集的已排序流并最终分配给另一个变量:

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

你刚刚错过了分配结果

请改用list.sort

 list.sort((o1, o2) -> o1.getItem().getValue().compareTo(o2.getItem().getValue())); 

并使用Comparator.comparing使其更简洁:

 list.sort(Comparator.comparing(o -> o.getItem().getValue())); 

在其中任何一个之后, list本身将被排序。

您的问题是list.stream.sorted 返回已排序的数据,它不会按照您的预期进行排序。

它似乎工作正常:

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

输入/输出示例

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

你确定你没有validation列表而不是sortedList [在上面的例子],即你是否将stream()的结果存储在一个新的List对象中并validation该对象?

 Collection> itemCollection = basket.values(); Iterator> itemIterator = itemCollection.stream().sorted(new TestComparator()).collect(Collectors.toList()).iterator(); package com.ie.util; import com.ie.item.Item; import java.util.Comparator; import java.util.Iterator; import java.util.Map; import java.util.Set; public class TestComparator implements Comparator> { // comparator is used to sort the Items based on the price @Override public int compare(Map o1, Map o2) { // System.out.println("*** compare method will be called *****"); Item item1 = null; Item item2 = null; Set itemSet1 = o1.keySet(); Iterator itemIterator1 = itemSet1.iterator(); if(itemIterator1.hasNext()){ item1 = itemIterator1.next(); } Set itemSet2 = o2.keySet(); Iterator itemIterator2 = itemSet2.iterator(); if(itemIterator2.hasNext()){ item2 = itemIterator2.next(); } return -item1.getPrice().compareTo(item2.getPrice()); } } 

****这有助于对嵌套的地图对象进行排序,例如Map>这里我根据Item对象价格排序。