Java Map Sort sortMapDesc(Map map)

Here you can find the source of sortMapDesc(Map map)

Description

sort Map Desc

License

Open Source License

Declaration

public static Map<String, Float> sortMapDesc(Map<String, Float> map) 

Method Source Code

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

import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

public class Main {
    public static Map<String, Float> sortMapDesc(Map<String, Float> map) {
        List<Entry<String, Float>> list = new LinkedList<Entry<String, Float>>(map.entrySet());

        // sort list based on comparator
        Collections.sort(list, new Comparator<Entry<String, Float>>() {
            public int compare(Entry<String, Float> o1, Entry<String, Float> o2) {
                return o2.getValue().compareTo(o1.getValue());
            }/* w  w w.  ja  va  2s  .c om*/
        });

        // put sorted list into map again
        //LinkedHashMap make sure order in which keys were inserted
        Map<String, Float> sortedMap = new LinkedHashMap<String, Float>();
        for (Iterator<Entry<String, Float>> it = list.iterator(); it.hasNext();) {
            Map.Entry<String, Float> entry = (Map.Entry<String, Float>) it.next();
            sortedMap.put(entry.getKey(), entry.getValue());
        }
        return sortedMap;
    }

    public static Map<Integer, Integer> sortMapDesc(HashMap<Integer, Integer> mapCorrectDomainPosition) {
        List<Entry<Integer, Integer>> list = new LinkedList<Entry<Integer, Integer>>(
                mapCorrectDomainPosition.entrySet());

        // sort list based on comparator
        Collections.sort(list, new Comparator<Entry<Integer, Integer>>() {
            public int compare(Entry<Integer, Integer> o1, Entry<Integer, Integer> o2) {
                return o2.getValue().compareTo(o1.getValue());
            }
        });

        // put sorted list into map again
        //LinkedHashMap make sure order in which keys were inserted
        Map<Integer, Integer> sortedMap = new LinkedHashMap<Integer, Integer>();
        for (Iterator<Entry<Integer, Integer>> it = list.iterator(); it.hasNext();) {
            Map.Entry<Integer, Integer> entry = (Map.Entry<Integer, Integer>) it.next();
            sortedMap.put(entry.getKey(), entry.getValue());
        }
        return sortedMap;
    }
}

Related

  1. sortMapByValue(Map oriMap)
  2. sortMapByValue(Map oriMap, final boolean isDesc)
  3. sortMapByValues(Map map, final boolean inverted)
  4. sortMapByValuesDecreasing( final Map mapToSort)
  5. sortMapByValuesDescending( Map aMap)
  6. sortMapDescByValue(Map map)
  7. sortMapDescendingByValue(Map unsortedMap)
  8. sortMapUsingComparator(final Map map, final Comparator comparator)
  9. sortParams(Map params)