-4

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

Pshemo
  • 122,468
  • 25
  • 185
  • 269
Spandan
  • 11
  • 6
  • You can't sort a `HashMap`. If you need to sort it, switch to a `TreeMap`. – Ayrton Feb 27 '19 at 15:43
  • Hello and welcome to StackOverflow! You seem to be under the impression... wait a minute... you are a member of two years?! – Turing85 Feb 27 '19 at 15:43
  • @Turing85 Did you notice that this is self-answered question so probably none of mentioned `idownvotedbecau.se` reasons apply here since: OP posted his code (in answer but still), which shows attempt, and was probably written after some research :) – Pshemo Feb 27 '19 at 15:54
  • @Pshemo huh true that ^^ will remove those comment – Turing85 Feb 27 '19 at 16:00

2 Answers2

0

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());
        }
    }
}
Pshemo
  • 122,468
  • 25
  • 185
  • 269
Spandan
  • 11
  • 6
  • Why not edit your last answer instead of adding a new answer? Beside from that, your "explanation" is pretty minimal. – Turing85 Feb 27 '19 at 15:50
  • Hello @Spandan. While it is nice of you to want to share some knowledge, try make sure that you don't duplicate already asked questions like [Sort a Map by values](https://stackoverflow.com/q/109383). We try to centralize knowledge about specific subject in one place to make it easier to find (or correct if needed correct). We also mark other questions on same subject as duplicates to point others to that main question. Also make sure that you are not repeating already provided solutions. Aside from that you should be fine (at least in self-answering questions section). Good luck! – Pshemo Feb 27 '19 at 16:23
  • @Turing85, It is two different ways to do the same. – Spandan Feb 28 '19 at 11:31
  • @Pshemo, I have shared a answer which is mostly as a util Class which will sort the Map based on requirement as 1. Sort by Key and 2. Sort by Value. It was our business requirement, Also I have used LinkedHashMap because our requirement was to Sort partial Data not all so in that context I have shared my effort so that Other can also refer, If Required. – Spandan Feb 28 '19 at 11:35
  • @Turing85 and Pshemo It wold be a great pleasure if you will review it and provide your vote, It will give me some confidence to do the same in future also. Thanks a lot in advance !!! – Spandan Feb 28 '19 at 11:49
  • Sorry, but I up-vote posts only when: (1) it was helpful for me - it solved problem I was facing (2) it is interesting - it tough me something new which I can use in the future (3) it is very well written - in a way which can be really helpful for those who are new on the subject (it covers topic/problem "from A to Z" so it: explains what problem/error means; why it occurred; *describes* idea behind possible solution; shows solution as code). Unfortunately (1) and (2) are not the case, but when you improve it to fulfill point (3) let me know. – Pshemo Feb 28 '19 at 12:36
  • BTW `MapComparatorToSortByKey` or `MapComparatorToSortByValue` are already provided by Java. Since version 8 we have `Map.Entry.comparingByKey()` `Map.Entry.comparingByValue()` methods which return appropriate Comparators. Also you don't need to use Iterator explicitly to print all values, use `for(Element el : elements)` which uses iterator implicitly. Another thing: `for(;condition;)` is a lot clearer with `while(condition)`. – Pshemo Feb 28 '19 at 12:36
  • Yet another improvement: when you create instance of generic type, you don't need to repeat generic type settings from type variable. It can let compiler infer it with diamond operator `<>`, so if you want to create `Foo>>>>` just write `Foo>>>> foo = new FooImpl<>();`. – Pshemo Feb 28 '19 at 12:47
-1
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());
    }
}
Spandan
  • 11
  • 6
  • 3
    code-only answers are highly discouraged. You should explain the problem at hand, as well as the way your solutoin solves the problem. No, I did not downvote your answer. – Turing85 Feb 27 '19 at 15:44
  • 1
    Don't reinvent the wheel. `TreeMap` already does this and is heavily optimized. – BackSlash Feb 27 '19 at 15:46
  • @BackSlash, It was our business requirement, Also I have used LinkedHashMap because our requirement was to Sort partial Data not all so in that context I have shared my effort so that Other can also refer, If Required. Also I am returnning Map so It will work with almost all the sub-type. It wold be a great pleasure if you will review it and provide your vote, It will give me some confidence to do the same in future also. Thanks a lot in advance !!! – Spandan Feb 28 '19 at 12:05
  • @Turing85, Thanks a lot for your input and indirect support !!! Sure I will take care of this from next time. – Spandan Feb 28 '19 at 12:06