我有一个Map,需要根据多个条件对Key进行排序.如何使用
Java 8 Comparator和Stream实现这一目标?
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<>();
>按键排序,按字母顺序排列
>根据List< MyObject>的大小对键进行排序
>根据最大MyObject countStuff()的大小对Key进行排序;
如果没有,那还有更好的方法吗?
更新1:
我想我有1& 2完成了.只是不确定如何做3.
Comparator<Entry<String, List<MyObject>>> comparator = Comparator.comparing(Map.Entry<String, List<MyObject>>::getKey)
.thenComparingInt(e -> e.getValue().size());
更新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());
最佳答案 HashMap不是排序的理想选择,您可以使用TreeMap,并将比较器传递给构造函数:
SortedMap<String, List<MyObject>> sorted = new TreeMap<>(comparator);
编辑:比较器仅适用于键而非值