-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

4
  • You can't sort a HashMap. If you need to sort it, switch to a TreeMap. Commented Feb 27, 2019 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?! Commented Feb 27, 2019 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 :) Commented Feb 27, 2019 at 15:54
  • @Pshemo huh true that ^^ will remove those comment Commented Feb 27, 2019 at 16:00

2 Answers 2

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()); } } } 
Sign up to request clarification or add additional context in comments.

8 Comments

Why not edit your last answer instead of adding a new answer? Beside from that, your "explanation" is pretty minimal.
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<Key, Value> by values. 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!
@Turing85, It is two different ways to do the same.
@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.
@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 !!!
|
-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()); } } 

4 Comments

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.
Don't reinvent the wheel. TreeMap already does this and is heavily optimized.
@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 !!!
@Turing85, Thanks a lot for your input and indirect support !!! Sure I will take care of this from next time.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.