Java Map Sort sortMapByValue(Map oriMap)

Here you can find the source of sortMapByValue(Map oriMap)

Description

sort Map By Value

License

Apache License

Declaration

public static Map<String, String> sortMapByValue(Map<String, String> oriMap) 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.util.*;

public class Main {
    public static Map<String, String> sortMapByValue(Map<String, String> oriMap) {
        Map<String, String> sortedMap = new LinkedHashMap<String, String>();
        if (oriMap != null && !oriMap.isEmpty()) {
            List<Map.Entry<String, String>> entryList = new ArrayList<Map.Entry<String, String>>(oriMap.entrySet());
            Collections.sort(entryList, new Comparator<Map.Entry<String, String>>() {
                public int compare(Map.Entry<String, String> entry1, Map.Entry<String, String> entry2) {
                    int value1 = 0, value2 = 0;
                    try {
                        value1 = Integer.parseInt(entry1.getValue());
                        value2 = Integer.parseInt(entry2.getValue());
                    } catch (NumberFormatException e) {
                        value1 = 0;//from  w  ww .  j  ava 2  s  .co  m
                        value2 = 0;
                    }
                    return value2 - value1;
                }
            });
            Iterator<Map.Entry<String, String>> iter = entryList.iterator();
            Map.Entry<String, String> tmpEntry = null;
            while (iter.hasNext()) {
                tmpEntry = iter.next();
                sortedMap.put(tmpEntry.getKey(), tmpEntry.getValue());
            }
        }
        return sortedMap;
    }
}

Related

  1. sortMapByValue(Map map, Comparator> valueComparator)
  2. sortMapByValue(Map map, Comparator> comparator)
  3. sortMapByValue(Map map, final boolean descending)
  4. sortMapByValue(Map oriMap)
  5. sortMapByValue(Map unsortMap, boolean highFirst)
  6. sortMapByValue(Map oriMap, final boolean isDesc)
  7. sortMapByValues(Map map, final boolean inverted)
  8. sortMapByValuesDecreasing( final Map mapToSort)
  9. sortMapByValuesDescending( Map aMap)