1 Mar 2018

Write a program to sort Map based on value in java .


To Sort the Map based on the value, we can use following ways to solve the problem. These are

       1.      By Using TreeMap with Comparator

       2.      By Using Comparator with help of List and Set

       3.      By Using  Java 8 features


Method#1 :: By Using TreeMap with Comparator

import java.util.Comparator;
import java.util.HashMap;
import java.util.TreeMap;

public class SortMapByValue {

            public static void main(String[] args) {
                        HashMap<String, Integer> map = new HashMap<String, Integer>();
                        map.put("a", 10);
                        map.put("b", 30);
                        map.put("c", 50);
                        map.put("d", 40);
                        map.put("e", 20);
                        System.out.println(map);

                        TreeMap<String, Integer> sortedMap = sortMapByValue(map);
                        System.out.println(sortedMap);
            }

            public static TreeMap<String, Integer> sortMapByValue(HashMap<String, Integer> map) {
                        Comparator<String> comparator = new ValueComparator(map);
                        // TreeMap is a map sorted by its keys.
                        // The comparator is used to sort the TreeMap by keys.
                        TreeMap<String, Integer> result = new TreeMap<String, Integer>(comparator);
                        result.putAll(map);
                        return result;
            }
}
// a comparator that compares Strings
class ValueComparator implements Comparator<String> {

            HashMap<String, Integer> map = new HashMap<String, Integer>();

            public ValueComparator(HashMap<String, Integer> map) {
                        this.map.putAll(map);
            }

            @Override
            public int compare(String s1, String s2) {
                        if (map.get(s1) >= map.get(s2)) {
                                    return -1;
                        } else {
                                    return 1;
                        }
            }
}
Output:
Before Sorting:: {a=10, b=30, c=50, d=40, e=20}
After sorting :: {c=50, d=40, b=30, e=20, a=10}

Method#2:: By Using Comparator with help of List and Set

import java.util.*;
import java.util.Map.Entry;

public class MApSortByValue {
            public static void main(String a[]) {
                        Map<String, Integer> map = new HashMap<String, Integer>();
                        map.put("Z", 20);
                        map.put("G", 45);
                        map.put("H", 22);
                        map.put("V", 67);
                        map.put("C", 26);
                        Set<Entry<String, Integer>> set = map.entrySet();
                        List<Entry<String, Integer>> list = new ArrayList<Entry<String, Integer>>(set);
                        Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
                                    public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
                                                return (o2.getValue()).compareTo(o1.getValue());
                                    }
                        });
                        for (Map.Entry<String, Integer> entry : list) {
                                    System.out.println("Key:"+entry.getKey() + " , Value:" + entry.getValue());
                        }
            }
}
Output:
Key:V , Value:67
Key:G , Value:45
Key:C , Value:26
Key:H , Value:22
Key:Z , Value:20

Method#3 :: By Using  Java 8 features

import java.util.*;
import java.util.stream.*;

class SortMapByValueDemo {
            public static void main(String[] args) {
                        Map<String, Integer> map = new HashMap<String, Integer>();
                        map.put("A", 20);
                        map.put("G", 45);
                        map.put("Z", 22);
                        map.put("V", 67);
                        map.put("C", 26);
                        Map<String, Integer> newMapSortedByValue1 = map.entrySet().stream()
                                                .sorted(Map.Entry.<String, Integer> comparingByValue().reversed())
                                                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));
                        // Uses custom comparator
                        Map<String, Integer> newMapSortedByValue2 = map.entrySet().stream()
                                                .sorted((e1, e2) -> e1.getValue().compareTo(e2.getValue()))
                                                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));

                        System.out.println(newMapSortedByValue1);// Dcreasing Order
                        System.out.println(newMapSortedByValue2);// Increasing Order
            }
}
Output:
Decreasing Order:: {V=67, G=45, C=26, Z=22, A=20}
Increasing Order:: {A=20, Z=22, C=26, G=45, V=67}

No comments:

Post a Comment