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
之所以引发,是因为合并器功能仅用于并行流],而我们并未使用。
comparingByValue
如果您觉得可读性更好,也可以使用:
import static java.util.Map.Entry.comparingByValue;Map<String, List<String>> sorted = map.entrySet().stream() .sorted(comparingByValue(comparingInt(List::size))) // ... as above