Tuesday, 15 May 2018



Sort or order a HashMap or TreeSet or any map item by value. Write a comparator
which compares by value, not by key. Entry class might hleps you here.


package govind;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
public class HashMapSortingBasedOnValue{
            public static void main(String[] args) {
                        Map<String, Integer> m=new HashMap<>();
                        m.put("one", 1);
                        m.put("five", 5);
                        m.put("two", 2);
                        m.put("four", 4);
                        m.put("three", 3);
                        System.out.println("-----------Before Soring Map Value-----------");
                        System.out.println(m);
                        System.out.println("---------------After Sorting(based on value)----------------");
            Set<Entry<String, Integer>> set = m.entrySet();
            List<Entry<String, Integer>> l=new ArrayList<>(set);
            Collections.sort(l, new Comparator<Map.Entry<String, Integer>>() {
      @Override
                        public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
           
                                    return (o1.getValue()).compareTo(o2.getValue());
                        }
            });
                System.out.println("--------------iterate through iterator---------------");
                        Iterator<Entry<String, Integer>> it = l.iterator();
                        while(it.hasNext())
                        {
                                    Entry<String, Integer> kk = it.next();
                                    System.out.println(kk.getKey()+" "+kk.getValue());
                        }
                       
                        System.out.println("-----------Through  for each loop------------");
                         for(Map.Entry<String, Integer> entry:l){
                        System.out.println(entry.getKey()+" ==== "+entry.getValue());
                    }
            }
}


o/p:----------------------------

-----------Before Soring Map Value-----------
{four=4, one=1, five=5, two=2, three=3}
---------------After Sorting( based on value) ----------------
--------------iterate through iterator---------------
one 1
two 2
three 3
four 4
five 5
-----------Through  for each loop------------
one ==== 1
two ==== 2
three ==== 3
four ==== 4
five ==== 5

No comments:

Post a Comment