I have a hashmap like the following
HashMap> map=new HashMap>();
map.put("USA", Arrays.asList("CA","IA","IL"));
map.put("India", Arrays.asList("MUM","CAL"));
map.put("Canada", Arrays.asList("TOR"));
I want to sort the map depending on the size of the list in the value in ascending order.How can i do that. Is there any nice method to do so?
解决方案
import static java.util.Comparator.comparingInt;
import static java.util.stream.Collectors.toMap;
Map> 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
));
You can replace comparingInt(e->e.getValue().size()) with comparingByValue(comparingInt(List::size)) if you find that more readable