问题
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<Long, String> 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 LinkedHashMap
here and use fancy functional programming to do the job in one line.
回答1:
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));
回答2:
Use toMap()
of java.util.stream.Collectors
来源:https://stackoverflow.com/questions/29721095/converting-a-collection-to-map-by-sorting-it-using-java-8-streams