I have a list that I need to custom sort it first and then convert it to a map with it's Id vs name map. Here is the code that will do the job but ---
Map map = new LinkedHashMap<>();
list.stream().sorted(Comparator.comparing(Building::getName)).forEach(b-> map.put(b.getId(), b.getName()));
I think this will do the job but I wonder if I can avoid creating linked hash map here and just like fancy functional programming do the job in one line?
解决方案
You have Collectors.toMap for that purpose :
Map 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 map =
list.stream()
.sorted(Comparator.comparing(Building::getName))
.collect(Collectors.toMap(Building::getId,
Building::getName,
(v1,v2)->v1,
LinkedHashMap::new));