这是我所拥有的,我想对条目中的值进行降序排序。
Map<String, Outer> outer = Input
.entrySet()
.stream
.collect(toMap(Map.Entry::getKey, entry->{
List<Outer> inner = entry
.getValue()
.stream()
.sorted(Comparator.comparingDouble(???))
})) ... (more lines of code.)
如何编写带有排序的比较器。 如果想在排序后执行以下操作
if (o1.getSomething() > o2.getSomething())
return -1;
if (o1.getSomething() < o2.getSomething())
return 1;
return 0;
获取列表并对其进行排序后,它对我有用。
inner.sort((Outer o1, Outer o2) -> {
if (o1.getSomething() > o2.getSomething())
return -1;
if (o1.getSomething() < o2.getSomething())
return 1;
return 0;
});
但是有没有办法在条目内使用stream.sorted(“在此处使用相同的比较器逻辑”)。
Entry 是一个 ArrayList,包含一堆值。
entry:[{w:1},{w:2},{w:3},{w:4}];
所以我想对其进行反向排序,如下所示:
entry:[{w:4},{w:3},{w:2},{w:1}];
所以我得到的最终列表是按相反顺序排序的。
抱歉造成困惑。
最佳答案
您可以定义Comparator
,然后使用stream.sorted()
,如下所示,并带有内联注释:
//Define comparator Lamda exp for Outer class
Comparator<Outer> outerComparator = (o1, o2) -> {
if (o1.getValue() > o2.getValue())
return -1;
else if (o1.getValue() < o2.getValue())
return 1;
else
return 0;
};
Map<String, Outer> output = Input.entrySet(). //get elements
stream(). //get elements
sorted( //sort elements by passsing outerComparator
Map.Entry.<String, Outer>comparingByValue(outerComparator)
.reversed())//reverse for descending order
.collect(Collectors.toMap(Map.Entry::getKey,
Map.Entry::getValue));//collect to Map object
关于java - 如何为 Map.Entry 内的 Map 值编写 java 8 比较器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43146640/