更新时间:2023-02-23 11:07:37
提取列表中的条目,然后对列表进行排序:
Extract the entries in a list, then sort the list :
List<Map.Entry<String, String>> entries = new ArrayList<Map.Entry<String, String>>(map.entries());
Collections.sort(entries, new Comparator<Map.Entry<String, String>>() {
@Override
public int compare(Map.Entry<String, String> e1, Map.Entry<String, String> e2) {
return Ints.compare(map.get(e2.getKey()).size(), map.get(e1.getKey()).size());
}
});
然后迭代条目。
编辑:
如果您想要的实际上是迭代内部地图的条目(条目< String,Collection< String>>
),然后执行以下操作:
If what you want is in fact iterate over the entries of the inner map (Entry<String, Collection<String>>
), then do the following :
List<Map.Entry<String, Collection<String>>> entries =
new ArrayList<Map.Entry<String, Collection<String>>>(map.asMap().entrySet());
Collections.sort(entries, new Comparator<Map.Entry<String, Collection<String>>>() {
@Override
public int compare(Map.Entry<String, Collection<String>> e1,
Map.Entry<String, Collection<String>> e2) {
return Ints.compare(e2.getValue().size(), e1.getValue().size());
}
});
// and now iterate
for (Map.Entry<String, Collection<String>> entry : entries) {
System.out.println("Key = " + entry.getKey());
for (String value : entry.getValue()) {
System.out.println(" Value = " + value);
}
}