Java Map Sort sortByComparator(Map unsortMap)

Here you can find the source of sortByComparator(Map unsortMap)

Description

sort Map by key desc

License

Open Source License

Parameter

Parameter Description
unsortMap a parameter

Declaration

@SuppressWarnings({ "unchecked", "rawtypes" })
public static Map sortByComparator(Map unsortMap) 

Method Source Code

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

import java.util.Collections;
import java.util.Comparator;

import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

public class Main {
    /**//from  w  w  w . j  a  v a2  s .  c o m
     * sort Map by key desc
     * 
     * @param unsortMap
     * @return
     */
    @SuppressWarnings({ "unchecked", "rawtypes" })
    public static Map sortByComparator(Map unsortMap) {

        List list = new LinkedList(unsortMap.entrySet());

        // sort list based on comparator
        Collections.sort(list, new Comparator() {
            public int compare(Object o1, Object o2) {
                return ((Comparable) ((Map.Entry) (o1)).getKey()).compareTo(((Map.Entry) (o2)).getKey());
            }
        });

        // put sorted list into map again
        Map sortedMap = new LinkedHashMap();
        for (Iterator it = list.iterator(); it.hasNext();) {
            Map.Entry entry = (Map.Entry) it.next();
            sortedMap.put(entry.getKey(), entry.getValue());
        }
        return sortedMap;
    }
}

Related

  1. sort(Map map, Comparator> comparator)
  2. sort(Map map)
  3. sort(Map src)
  4. sort(T map, Comparator> c)
  5. sortBy(Collection collection, final Map valuesMap)
  6. sortByComparator(Map unsortMap)
  7. sortByComparatorDecreasing(Map unsortMap)
  8. sortByComparatorDouble( final Map map)
  9. sortByDescendingValues(Map unsortMap)