Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert List to map using java 8

I am working on sorting a map by values code using java 8.

I have done most of the thing but I am not getting how to convert the list to map using java 8 features

public class SortMapByValue {
public static void main(String[] args) {
    HashMap<String, Integer> map = new HashMap<>();
    map.put("A", 3);
    map.put("V", 1);
    map.put("Anss", 9);
    map.put("D", 5);
    map.put("E", 2);
    map.put("F", 10);

    HashMap<String, Integer> newMap = new LinkedHashMap<>();

    List<Map.Entry<String, Integer>> list = new ArrayList<>(map.entrySet());


    Collections.sort(list, (o1, o2) -> o1.getValue() - o2.getValue());

    // Need to this using Java 8 -- start

    for (Entry<String, Integer> entry : list) {
        newMap.put(entry.getKey(), entry.getValue());
    } 

    // Need to this using Java 8 -- end

    newMap.forEach((k, v) -> System.out.println("Key : " + k + " Value : " + v));

    }
}
like image 927
testMyUnderstanding Avatar asked May 25 '19 18:05

testMyUnderstanding


2 Answers

If you want to sort Map based on values use Entry.comparingByValue() and then collect them to LinkedHashMap :

Map<String,Integer> result =   map.entrySet()
       .stream()
       .sorted(Entry.comparingByValue())
       .collect(Collectors.toMap(Entry::getKey, Entry::getValue, (a,b) -> b, LinkedHashMap::new));

In Java-8 there are three overloaded toMap method, the above one is with 4 Parameters which is

public static <T,K,U,M extends Map<K,U>> Collector<T,?,M> toMap(Function<? super T,? extends K> keyMapper,
                                                            Function<? super T,? extends U> valueMapper,
                                                            BinaryOperator<U> mergeFunction,
                                                            Supplier<M> mapSupplier)

Parameters:

keyMapper - a mapping function to produce keys

valueMapper - a mapping function to produce values

mergeFunction - a merge function, used to resolve collisions between values associated with the same key, as supplied to Map.merge(Object, Object, BiFunction)

mapSupplier - a function which returns a new, empty Map into which the results will be inserted

like image 52
Deadpool Avatar answered Sep 30 '22 11:09

Deadpool


Map map = list.stream().collect(
    Collectors.toMap(
        entry -> entry.getKey(), // keyMapper
        entry -> entry.getValue(), // valueMapper
        (first, second) -> first,  // mergeFunction
        () -> new LinkedHashMap<>() // mapFactory
    )
);

See Stream and Collectors

you can even do that:

public static void main(String[] args) {
        HashMap<String, Integer> map = new HashMap<>();
        map.put("A", 3);
        map.put("V", 1);
        map.put("Anss", 9);
        map.put("D", 5);
        map.put("E", 2);
        map.put("F", 10);

        Map newMap = map.entrySet().stream()
            .sorted(Map.Entry.comparingByValue())
            .collect(
                Collectors.toMap(
                    entry -> entry.getKey(), // keyMapper
                    entry -> entry.getValue(), // valueMapper
                    (first, second) -> first,  // mergeFunction
                    () -> new LinkedHashMap<>() // mapFactory
                )
            );

        newMap.forEach((k, v) -> System.out.println("Key : " + k + " Value : " + v));

    }
like image 21
6pi Avatar answered Sep 30 '22 11:09

6pi