Sort a Map by key or Value in Java [duplicate]

2019-09-29 04:49发布

问题:

This question already has an answer here:

  • Sort a Map<Key, Value> by values 51 answers
  • How to sort Map values by key in Java? 13 answers

Sort a Map by Key or by value in java

Input Map 1-eee 4-ddd 5-ccc 0-bbb 3-aaa

1st Output Map(By-Key): 0-bbb 1-eee 3-aaa 4-ddd 5-ccc
2nd Output Map(By-Value): 3-aaa 0-bbb 5-ccc 4-ddd 1-eee

回答1:

This code will first sort the map by Key and then by value.
Just write a main method and call this method as follow:

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

public class SortMapByKeyAndValue
{
    public static void main(String[] args)
    {
        aMapSortProgramByKeyAndValue();
    }

    private static void aMapSortProgramByKeyAndValue()
    {
        Map<String, Integer> myMap = new HashMap<String, Integer>();
        // putting values in the Map
        myMap.put("Jayant", 80);
        myMap.put("Abhishek", 90);
        myMap.put("Anushka", 80);
        myMap.put("Amit", 75);
        myMap.put("Spandan", 50);
        myMap.put("Hari", 55);
        myMap.put("Keshav", 60);

        System.out.println("Map data without Sort :-");
        for (Entry<String, Integer> myEntryMapData : myMap.entrySet())
        {
            System.out.println("The Map data is Key: " + myEntryMapData.getKey() + " Value: "
                    + myEntryMapData.getValue());
        }

        List<Entry<String, Integer>> myMapDataAsList = new ArrayList<Map.Entry<String, Integer>>();
        myMapDataAsList.addAll(myMap.entrySet());

        System.out.println("Map data Stored in List, The whole List is : " + myMapDataAsList);

        Iterator<Entry<String, Integer>> myListIterator = myMapDataAsList.iterator();
        System.out.println("Map data Stored in List, Print through iterator :-");

        for (; myListIterator.hasNext();)
        {
            Entry<String, Integer> myListData = myListIterator.next();
            System.out.println("The List data is Key: " + myListData.getKey() + " Value: " + myListData.getValue());
        }

        Collections.sort(myMapDataAsList, new Comparator<Entry<String, Integer>>()
        {

            @Override
            public int compare(Entry<String, Integer> dataOne, Entry<String, Integer> dataTwo)
            {
                return dataOne.getKey().compareTo(dataTwo.getKey());
            }

        });

        System.out.println("After Sort by the Key the Map data is : ");
        myListIterator = myMapDataAsList.iterator();
        for (; myListIterator.hasNext();)
        {
            Entry<String, Integer> myListData = myListIterator.next();
            System.out.println("The List data is Key: " + myListData.getKey() + " Value: " + myListData.getValue());
        }

        Collections.sort(myMapDataAsList, new Comparator<Entry<String, Integer>>()
        {

            @Override
            public int compare(Entry<String, Integer> dataOne, Entry<String, Integer> dataTwo)
            {
                return dataOne.getValue().compareTo(dataTwo.getValue());
            }

        });

        System.out.println("After Sort by the vale the Map data is : ");
        myListIterator = myMapDataAsList.iterator();
        for (; myListIterator.hasNext();)
        {
            Entry<String, Integer> myListData = myListIterator.next();
            System.out.println("The List data is Key: " + myListData.getKey() + " Value: " + myListData.getValue());
        }
    }
}


回答2:

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

public class MapSortUtil
{
    public static Map<String, String> sortMapByKey(Map<String, String> anUnSortedMap)
    {
        List<Entry<String, String>> myListOfEntrySet = getListOfEntrySetFromMap(anUnSortedMap);

        /* Sort the list of entry-set in ascending order. */
        Collections.sort(myListOfEntrySet, new MapComparatorToSortByKey());

        /* Generating new Map from Sorted Entry List. */
        Map<String, String> mySortedMap = getSortedMapFromSortedEntry(myListOfEntrySet);

        return mySortedMap;
    }

    public static Map<String, String> sortMapByValue(Map<String, String> anUnSortedMap)
    {
        List<Entry<String, String>> myListOfEntrySet = getListOfEntrySetFromMap(anUnSortedMap);

        /* Sort the list of entry-set in ascending order. */
        Collections.sort(myListOfEntrySet, new MapComparatorToSortByValue());

        /* Generating new Map from Sorted Entry List. */
        Map<String, String> mySortedMap = getSortedMapFromSortedEntry(myListOfEntrySet);

        return mySortedMap;
    }

    private static List<Entry<String, String>> getListOfEntrySetFromMap(Map<String, String> anUnSortedMap)
    {
        /* Getting Entry Set from the Map. */
        Set<Entry<String, String>> myEntrySetOfMap = anUnSortedMap.entrySet();

        /* Creating List of Entry Set. */
        List<Entry<String, String>> myListOfEntrySet = new LinkedList<Map.Entry<String, String>>(myEntrySetOfMap);

        return myListOfEntrySet;
    }

    private static Map<String, String> getSortedMapFromSortedEntry(List<Entry<String, String>> myListOfEntrySetOfMap)
    {
        /* Add Sorted list in new LinkedHashMap one-by-one. */
        Map<String, String> mySortedLinkedHashMap = new LinkedHashMap<String, String>();
        for (Entry<String, String> myOneByOneData : myListOfEntrySetOfMap)
        {
            mySortedLinkedHashMap.put(myOneByOneData.getKey(), myOneByOneData.getValue());
        }

        return mySortedLinkedHashMap;
    }
}

class MapComparatorToSortByValue implements Comparator<Entry<String, String>>
{
    @Override
    public int compare(Entry<String, String> aMap1, Entry<String, String> aMap2)
    {
        return aMap1.getValue().compareTo(aMap2.getValue());
    }
}

class MapComparatorToSortByKey implements Comparator<Entry<String, String>>
{
    @Override
    public int compare(Entry<String, String> aMap1, Entry<String, String> aMap2)
    {
        return aMap1.getKey().compareTo(aMap2.getKey());
    }
}