我有一个像这样的HashMap
:
Map<String, List<String>> map = new HashMap<>();
map.put("USA", Arrays.asList("CA","IA","IL"));
map.put("India", Arrays.asList("MUM","CAL"));
map.put("Canada", Arrays.asList("TOR"));
我想根据列表值的大小对 map 进行升序排序。我该怎么做?
在这种情况下,我想订购加拿大、印度、美国的 key 。
最佳答案
HashMap
没有保证的迭代顺序,因此您需要收集到 LinkedHashMap
为了使排序有意义。
import static java.util.Comparator.comparingInt;
import static java.util.stream.Collectors.toMap;
Map<String, List<String>> sorted = map.entrySet().stream()
.sorted(comparingInt(e -> e.getValue().size()))
.collect(toMap(
Map.Entry::getKey,
Map.Entry::getValue,
(a, b) -> { throw new AssertionError(); },
LinkedHashMap::new
));
AssertionError
被抛出是因为组合器函数是 only used on parallel streams ,我们没有使用。
您还可以使用 comparingByValue
如果您发现它更具可读性:
import static java.util.Map.Entry.comparingByValue;
Map<String, List<String>> sorted = map.entrySet().stream()
.sorted(comparingByValue(comparingInt(List::size)))
// ... as above
关于java - 如何根据 Collection 值的大小对 Map 进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30853117/