I have a list that I need to custom sort and then convert to a map with its Id vs. name map.
Here is my code:
Map map = new Link
You have Collectors.toMap
for that purpose :
Map<Long, String> map =
list.stream()
.sorted(Comparator.comparing(Building::getName))
.collect(Collectors.toMap(Building::getId,Building::getName));
If you want to force the Map implementation that will be instantiated, use this :
Map<Long, String> map =
list.stream()
.sorted(Comparator.comparing(Building::getName))
.collect(Collectors.toMap(Building::getId,
Building::getName,
(v1,v2)->v1,
LinkedHashMap::new));
Use toMap()
of java.util.stream.Collectors