4
我有一個Map並需要根據多個條件對Key進行排序。如何使用Java 8 Comparator和Stream來實現這一點?基於最大MyObject countStuff();
如何在Java和Map上使用多個比較器的地圖和值屬性
如果沒有,有沒有更好的辦法的大小
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>
- 排序鍵的大小?
更新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());
你能否澄清一下'List .getListOfStuff()'應該做什麼?例如,它可以被重寫爲'list.stream()。filter(...)。count()'其中'list'是類型'List '? –
因此,您想要通過複雜排序條件排序映射,首先通過鍵,然後通過值屬性(列表大小,最大)排序?鑑於原始地圖是「HashMap」,鍵必須是唯一的;它們永遠不可能是平等的,所以永遠不需要檢查二級分類條件。 – AJNeufeld
'Comparator.comparing(Map.Entry> :: getKey' => Entry :: comparativeByKey' –
assylias