I have a List of String like:
List locations = Arrays.asList(\"US:5423\",\"US:6321\",\"CA:1326\",\"AU:5631\");
And I want to
Seems like your location map needs to be sorted based on keys, you can try the following
List locations = Arrays.asList("US:5423", "US:6321", "CA:1326", "AU:5631");
Map> locationMap = locations.stream().map(str -> str.split(":"))
.collect(() -> new TreeMap>(), (map, parts) -> {
if (map.get(parts[0]) == null) {
List list = new ArrayList<>();
list.add(parts[1]);
map.put(parts[0], list);
} else {
map.get(parts[0]).add(parts[1]);
}
}, (map1, map2) -> {
map1.putAll(map2);
});
System.out.println(locationMap); // this outputs {AU=[5631], CA=[1326], US=[5423, 6321]}