Java Map Sort sortMap(Map oldMap, final boolean asc)

Here you can find the source of sortMap(Map oldMap, final boolean asc)

Description

sort Map

License

Open Source License

Declaration

public static Map sortMap(Map oldMap, final boolean asc) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.util.*;

public class Main {

    public static Map sortMap(Map oldMap, final boolean asc) {
        if (null == oldMap) {
            return null;
        }//w w w  .j av a 2s.co  m
        ArrayList<Map.Entry<String, Integer>> list = new ArrayList<Map.Entry<String, Integer>>(oldMap.entrySet());
        Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
            public int compare(Map.Entry<String, Integer> arg0, Map.Entry<String, Integer> arg1) {
                if (asc) {
                    return arg0.getValue() - arg1.getValue();
                } else {
                    return arg1.getValue() - arg0.getValue();
                }

            }
        });
        Map newMap = new LinkedHashMap();
        for (int i = 0; i < list.size(); i++) {
            newMap.put(list.get(i).getKey(), list.get(i).getValue());
        }
        return newMap;
    }
}

Related

  1. sortKeysDesc(HashMap> hash)
  2. sortKeyValuePairByValue( Map map)
  3. sortMap(final Map map, final Comparator> comparator)
  4. sortMap(LinkedHashMap map, Comparator> c)
  5. sortMap(Map oldMap)
  6. sortMap(Map map, int k)
  7. sortMap(Map map, Comparator> compator)
  8. sortMapByKey(Map data)
  9. sortMapByKey(Map map)