Tuesday, May 8, 2012

Sorting Map based on values - java

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
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 MapValueSort {
 
    public static void main(String[] args){
        Map<String, Integer> unsortedData = new HashMap<String, Integer>();
        unsortedData.put("Left forehead",2);
        unsortedData.put("Right forehead",2);
        unsortedData.put("Right face",3);
        unsortedData.put("Left face",2);
     
        Set<Entry<String, Integer>>  entrySet = unsortedData.entrySet();
        List<MyEntry> sortedEntries =  new ArrayList<MyEntry>();
     
        for (Iterator iterator = entrySet.iterator(); iterator.hasNext();) {
            Entry<String, Integer> entry = (Entry<String, Integer>) iterator.next();
            sortedEntries.add(new MyEntry(entry));
        }
      
        Collections.sort(sortedEntries);
        Collections.reverse(sortedEntries);
        for(int i=0;i<sortedEntries.size();i++){
            System.out.println(sortedEntries.get(i).getKey()+" "+sortedEntries.get(i).getValue());
        }
    
        System.out.println("--------------->> unsortedData "+unsortedData);
        System.out.println("--------------->> entrySet "+entrySet);
        System.out.println("--------------->> sortedEntries "+sortedEntries);
    }
  
  
}
class MyEntry implements java.util.Map.Entry,Comparable<MyEntry>{
  
    private String key;
    private Integer value;
    public MyEntry(Entry<String, Integer> entry) {
        super();
        key = entry.getKey();
        value = entry.getValue();
    }

    @Override
    public Object getKey() {
        return key;
    }

    @Override
    public Object getValue() {
        return value;
    }

    @Override
    public Object setValue(Object value) {
        return null;
    }

    @Override
    public int compareTo(MyEntry o) {
        Integer currentValue = (Integer)this.getValue();
        Integer targetValue = (Integer)o.getValue();
        return currentValue.compareTo(targetValue);
    }
}

No comments:

Post a Comment