我有一个 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();
的大小对关键字进行排序
如果没有,有没有更好的方法?
更新 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);
编辑:比较器只适用于键而不适用于值
关于java - 如何使用 Java 8 在 Map 和 value 属性上使用多个比较器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41191595/