package com.zzsn.generation.test;

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

public class SortMap {
    public static void main(String[] args) throws Exception {
        // TODO code application logic here
        Map<String,Double> myMap = new LinkedHashMap<String,Double>();
        myMap.put("1", 1D);
        myMap.put("2", 4D);
        myMap.put("3", 3D);
        myMap.put("4", 9D);
        myMap.put("5", 6D);
        myMap.put("6", 2D);
        
        printMap(myMap);
        
        myMap = sortMap(myMap);
        
        printMap(myMap);
    }
    
    private static void printMap(Map map){
        System.out.println("===================mapStart==================");
        Iterator it = map.entrySet().iterator();
        while(it.hasNext()){
            Entry entry = (Entry) it.next();
            System.out.println(entry.getKey() + ":" + entry.getValue());
        }
        System.out.println("===================mapEnd==================");
    } 

    public static LinkedHashMap<String,Double> sortMap(Map<String,Double> oldMap) {
        ArrayList<Entry<String, Double>> list = new ArrayList<Entry<String, Double>>(oldMap.entrySet());
        Collections.sort(list, new Comparator<Entry<String, Double>>() {

            @Override
            public int compare(Entry<String, Double> arg0,
                    Entry<String, Double> arg1) {
                if(arg0.getValue() >arg1.getValue()){
                    return -1;
                }else if(arg0.getValue()<arg1.getValue()){
                    return 1;
                }else
                {
                    return 0;
                }
            }
        });
        LinkedHashMap<String,Double> newMap = new LinkedHashMap<String,Double>();
        for (int i = 0; i < list.size(); i++) {
            newMap.put(list.get(i).getKey(), list.get(i).getValue());
        }
        return newMap;
    }
    
    public static LinkedHashMap<String,Float> sortMapForTfIdf(Map<String,Float> oldMap) {
        ArrayList<Entry<String, Float>> list = new ArrayList<Entry<String, Float>>(oldMap.entrySet());
        Collections.sort(list, new Comparator<Entry<String, Float>>() {

            @Override
            public int compare(Entry<String, Float> arg0,
                    Entry<String, Float> arg1) {
                if(arg0.getValue() >arg1.getValue()){
                    return -1;
                }else if(arg0.getValue()<arg1.getValue()){
                    return 1;
                }else
                {
                    return 0;
                }
            }
        });
        LinkedHashMap<String,Float> newMap = new LinkedHashMap<String,Float>();
        for (int i = 0; i < list.size(); i++) {
            newMap.put(list.get(i).getKey(), list.get(i).getValue());
        }
        return newMap;
    }
}