sort Map By Comparator - Java Collection Framework

Java examples for Collection Framework:Map

Description

sort Map By Comparator

Demo Code


//package com.java2s;

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

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

public class Main {
    public static Map<String, Integer> sortByComparator(
            Map<String, Integer> unsortMap, final boolean order) {

        List<Map.Entry<String, Integer>> list = new LinkedList<Map.Entry<String, Integer>>(
                unsortMap.entrySet());/* w ww.  j av a 2  s  .c  o  m*/

        // Sorting the list based on values
        Collections.sort(list,
                new Comparator<Map.Entry<String, Integer>>() {
                    public int compare(Map.Entry<String, Integer> o1,
                            Map.Entry<String, Integer> o2) {
                        if (order) {
                            return o1.getValue().compareTo(o2.getValue());
                        } else {
                            return o2.getValue().compareTo(o1.getValue());

                        }
                    }
                });

        // Maintaining insertion order with the help of LinkedList
        Map<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
        for (Map.Entry<String, Integer> entry : list) {
            sortedMap.put(entry.getKey(), entry.getValue());
        }

        return sortedMap;
    }
}

Related Tutorials