28 Feb 2018

Write a program to sort a Map by Key in java.


To sort the Map based on the key we can use following methods. these are..
1.     Using TreeMap
2.     Using Comparator
3.   Using ArrayList
4.   Using java 8 features

Method#1 :: By Using TreeMap

When we use the TreeMap collection then ,according to the property of of TreeMap ,It will sort the Object based on the Key.TreeMap sort the Object in Ascending order of key.so the program to sort the Map based on key by using the TreeMap is following...

//Sort Map by key in Ascending Order(Using TreeMap)
import java.util.*;
class SortMapByKey {
            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);
                        TreeMap<String, Integer> tm = new TreeMap<>(map);
            for (Map.Entry<String, Integer> entry : tm.entrySet())
            System.out.println ("Key = " + entry.getKey() +", Value = " + entry.getValue());
            }
}

Output:
Key = A, Value = 20
Key = C, Value = 26
Key = G, Value = 45
Key = V, Value = 67
Key = Z, Value = 22

Method#2 :: By Using Comparator
Comparator is basically used for customised sorting so here we can use the   Comparator to sort the Map based on the key.the program for this is following...

import java.util.*;
import java.util.Map.Entry;
public class MApSortByKey {
            public static void main(String a[]) {
                  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);
                        Set<Entry<String, Integer>> set = map.entrySet();
                        List<Entry<String, Integer>> list = new ArrayList<Entry<String, Integer>>(set);
                        Collections.sort(listnew Comparator<Map.Entry<String, Integer>>() {
                        public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
                                                return (o2.getKey()).compareTo(o1.getKey());
                                    }
                        });
                        for (Map.Entry<String, Integer> entry : list) {
                                System.out.println("Key = " + entry.getKey() +", Value = " + entry.getValue());
                        }
            }
}

Output:
Key = Z, Value = 22
Key = V, Value = 67
Key = G, Value = 45
Key = C, Value = 26
Key = A, Value = 20

Method#3 :: By Using ArrayList

// Java Code to sort Map by key value
import java.util.*;

class SortMapByKeyTest {

            // This map stores unsorted values
            static Map<String, Integer> map = new HashMap<>();

            // Function to sort map by Key
            public static void sortbykey() {
                        ArrayList<String> sortedKeys = new ArrayList<String>(map.keySet());

                        Collections.sort(sortedKeys);

                        // Display the TreeMap which is naturally sorted
                        for (String x : sortedKeys)
                                    System.out.println("Key = " + x + ", Value = " + map.get(x));
            }

            // Driver Code
            public static void main(String args[]) {
                        // putting values in the Map
                        map.put("A", 20);
                        map.put("G", 45);
                        map.put("Z", 22);
                        map.put("V", 67);
                        map.put("C", 26);

                        // Calling the function to sortbyKey
                        sortbykey();
            }
}
Output:
Key = A, Value = 20
Key = C, Value = 26
Key = G, Value = 45
Key = V, Value = 67
Key = Z, Value = 22

Method#4 :: By Using Java 8 Features

in Java 8 we can make use of toMap() method in Collectors which takes following parameters:
·      keymapper: mapping function to produce keys
·      valuemapper: mapping function to produce values
·     mergeFunction: a merge function, used to resolve collisions between values associated with the same key
·      mapSupplier: a function which returns a new, empty Map into which the results will be inserted.

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

class SortMapByKeyDemo {
            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> newMapSortedByKey1 = map.entrySet().stream()
                                                .sorted(Map.Entry.<String, Integer> comparingByKey().reversed())
                                                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));
                        // Uses custom comparator
                        Map<String, Integer> newMapSortedByKey2 = map.entrySet().stream()
                                                .sorted((e1, e2) -> e1.getKey().compareTo(e2.getKey()))
                                                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));
                        System.out.println(newMapSortedByKey1);// Dcreasing Order
                        System.out.println(newMapSortedByKey2);// Increasing Order
            }
}

Output
{Z=22, V=67, G=45, C=26, A=20}
{A=20, C=26, G=45, V=67, Z=22}

No comments:

Post a Comment