如何使用Java 8在映射和值属性上使用多个比较器
我有一张地图,需要根据多种条件对密钥进行排序。如何使用Java8比较器和流来实现这一点如何使用Java 8在映射和值属性上使用多个比较器,java,java-8,comparator,Java,Java 8,Comparator,我有一张地图,需要根据多种条件对密钥进行排序。如何使用Java8比较器和流来实现这一点 class MyObject { private Set<Objects> setOfStuff; public Set<Objects> getSetOfStuff(){ return listOfStuff; } public int countStuff(){ return listOfStuff.size();
class MyObject {
private Set<Objects> setOfStuff;
public Set<Objects> getSetOfStuff(){
return listOfStuff;
}
public int countStuff(){
return listOfStuff.size();
}
}
Map<String, List<MyObject> needsSorting = new HashMap<>();
needsSorting.put("Monday", createSetOfObj());
needsSorting.put("Wednesday", createSetOfObj());
needsSorting.put("Thursday", createSetOfObj());
Set<MyObject> createSetOfObj() {
...
return list;
}
Map<String, Set<MyObject>> sortedResult = new LinkedHashMap<>();
更新2:
这似乎产生了我需要的比较。我添加了一个countStuff,便于查看大小
Comparator<Entry<String, Set<MyObject>>> comparator = Comparator.comparing(Map.Entry<String, Set<MyObject>>::getKey)
.thenComparingInt(e -> e.getValue().size())
.thenComparingInt(e -> e.getValue().stream().map(MyObject::countStuff).max(Integer::max).get());
Comparator Comparator=Comparator.comparating(Map.Entry::getKey)
.Then比较(e->e.getValue().size())
.thenComparingInt(e->e.getValue().stream().map(MyObject::countStuff).max(Integer::max.get());
HashMap不适合排序,您可以使用树映射来代替,并将比较器传递给构造函数:
SortedMap<String, List<MyObject>> sorted = new TreeMap<>(comparator);
SortedMap sorted=新树形图(比较器);
编辑:比较器只适用于键而不适用于值您能否澄清一下List.getListOfStuff()
应该做什么?例如,是否可以将其重写为list.stream().filter(…).count()
其中list
的类型为list
?因此,您希望按照复杂的排序条件对映射进行排序,首先按键,然后按值属性(列表大小,最大值)排序?假设原始映射是HashMap
,则键必须是唯一的;它们永远不可能相等,因此永远不需要检查二级排序条件。Comparator.comparating(Map.Entry::getKey
=>Entry::comparingByKey
.max(Integer::max)
绝对不会按您的意图执行。您可以执行.max(Comparator.naturalOrder())
或.reduce(Integer::max))
,但不要混淆它们。但是无论如何,使用e.getValue().stream().mapToInt(MyObject::countStuff).max().getAsInt()
代替Comparator.comparating(Map.Entry::getKey)
也可以使用Map.Entry.comparingByKey()
SortedMap<String, List<MyObject>> sorted = new TreeMap<>(comparator);