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.
Using Streams in Java 8 We will use the stream() method to get the stream of entrySet followed by the lambda expression inside sorted() method to sort the stream and finally, we will convert it into a map using toMap() method.
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With