Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a collection to Map by sorting it using java 8 streams

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.

like image 780
Mohammad Adnan Avatar asked Apr 18 '15 18:04

Mohammad Adnan


People also ask

How do you sort a map based on values in Java 8?

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.


1 Answers

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));
like image 153
Eran Avatar answered Oct 24 '22 17:10

Eran