Sort a map on key and value - java

I want to sort a Map on key and value. First on key then on value.
For example, this should be the result;
1,2
1,3
2,1
2,2
Anyone has a suggestion on how to achieve this effectively? I've been seeing people using a TreeMap to sort keys, however i also need values.
Or ofcouse any other method of sorting pairs on key and value is welcome.

import java.util.SortedSet;
import java.util.TreeSet;
public class SortMapOnKeyAndValue {
public static void main(String[] args) {
SortedSet<KeyValuePair> sortedSet = new TreeSet<KeyValuePair>();
sortedSet.add(new KeyValuePair(1, 2));
sortedSet.add(new KeyValuePair(2, 2));
sortedSet.add(new KeyValuePair(1, 3));
sortedSet.add(new KeyValuePair(2, 1));
for (KeyValuePair keyValuePair : sortedSet) {
System.out.println(keyValuePair.key+","+keyValuePair.value);
}
}
}
class KeyValuePair implements Comparable<KeyValuePair>{
int key, value;
public KeyValuePair(int key, int value) {
super();
this.key = key;
this.value = value;
}
public int compareTo(KeyValuePair o) {
return key==o.key?value-o.value:key-o.key;
}
}

What you are looking for a is SortedSetMultimap, part of Google's Guava library. The implementation they include is named TreeMultimap:
http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/collect/TreeMultimap.html
If you're not familiar with it, Guava is a fantastic library with lots of great stuff that you sometimes think should be in the standard Java libraries. I think Java 8, actually, will include some stuff from Guava (at least that seemed to me to be the drift of this item: http://openjdk.java.net/jeps/108).

Sounds like you want a multi map of some type e.g.
SortedMap<Key, SortedSet<Value>> map = new TreeMap<Key, SortedSet<Value>>();
map.put(1, new TreeSet<Integer>(Arrays.asList(1, 2)));
map.put(2, new TreeSet<Integer>(Arrays.asList(2, 1)));
System.out.println(map);
prints
{ 1 = {1, 2}, 2 = {1, 2}}

The other answers have indicated the problem with duplicate keys, but I am guessing you have pairs that you want to sort and the Map bit was just a mistake. The cleanest solution I can think of is to create a custom Pair class which implements Comparator and compares both the key and the value of two Pairs. You can then use Collections.sort to sort this.

If you are willing to take the risk, you could use the constructor that allows you to specify a Comparator: http://download.oracle.com/javase/1.5.0/docs/api/java/util/TreeMap.html#TreeMap%28java.util.Comparator%29
Having said that, what you want to do is ugly as hell and illegal because:
* the order will not be consistent with equals(), which is a requisite for SortedSet)
* the order may change due to altering values in the Map, and I don't know if its implementation allows for this.
I think that you need something else. Perhaps you would be better by creating an object that has both key and value and properly implements equals(), hashcode() and Comparable, and use a SortedSet with it.
EDIT: I have answered the generic question (sort a map on key and value) without looking at your samples. As others have written, you cannot have duplicate keys in a map.

It is not possible, because a map cannot contain duplicate keys. A TreeMap is always sorted by key value (assuming, the key type is Comparable).
But for those task we usually take a map whose values are lists:
Map<Integer, List<Integer>> map = new TreeMap<Integer, List<Integer>>();
// add some values in random order
List<Integer> list = new ArrayList<Integer>();
list.add(2);
list.add(1);
map.put(2,list);
list = new ArrayList<Integer>();
list.add(2);
list.add(1);
map.put(1,list);
// result
for (Integer key:map.keySet()) { // map is already sorted
List<Integer> value = map.get(key);
Collections.sort(value); // list of values needs sorting
for (Integer innerValue:value) {
System.out.printf("%s : %s%n", key, innerValue);
}
}

The overall idea is, convert the Map into List, sort the List and put the sorted list back to a Map.
Map ---> List ---> Sort ---> Map
Example
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
public class SortMyMap{
public static void main(String[] args) {
System.out.println("Unsort Map......");
Map<String,String> unsortMap = new HashMap<String,String>();
unsortMap.put("1", "1");
unsortMap.put("2", "A");
unsortMap.put("3", "2");
Iterator iterator=unsortMap.entrySet().iterator();
for (Map.Entry entry : unsortMap.entrySet()) {
System.out.println("Key : " + entry.getKey()
+ " Value : " + entry.getValue());
}
System.out.println("Sorted Map......");
Map<String,String> sortedMap = sortByComparator(unsortMap);
for (Map.Entry entry : sortedMap.entrySet()) {
System.out.println("Key : " + entry.getKey()
+ " Value : " + entry.getValue());
}
}
private 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)).getValue())
.compareTo(((Map.Entry) (o2)).getValue());
}
});
//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;
}
}

Please follow this code :-
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());
}
}
}

you can't have such map
1->11
1->21
the key '1' is common so 21 will replace 11

Related

sorting hashmap with Collections.sort restarts the sort once every few values [duplicate]

This question already has answers here:
Sort a Map<Key, Value> by values
(64 answers)
Closed 3 years ago.
How are we able to sort a HashMap<key, ArrayList>?
I want to sort on the basis of a value in the ArrayList.
Do you have to use a HashMap? If you only need the Map Interface use a TreeMap
If you want to sort by comparing values in the HashMap. You have to write code to do this, if you want to do it once you can sort the values of your HashMap:
Map<String, Person> people = new HashMap<>();
Person jim = new Person("Jim", 25);
Person scott = new Person("Scott", 28);
Person anna = new Person("Anna", 23);
people.put(jim.getName(), jim);
people.put(scott.getName(), scott);
people.put(anna.getName(), anna);
// not yet sorted
List<Person> peopleByAge = new ArrayList<>(people.values());
Collections.sort(peopleByAge, Comparator.comparing(Person::getAge));
for (Person p : peopleByAge) {
System.out.println(p.getName() + "\t" + p.getAge());
}
If you want to access this sorted list often, then you could insert your elements into a HashMap<TreeSet<Person>>, though the semantics of sets and lists are a bit different.
Sorted List by hasmap keys:
SortedSet<String> keys = new TreeSet<String>(myHashMap.keySet());
Sorted List by hashmap values:
SortedSet<String> values = new TreeSet<String>(myHashMap.values());
In case of duplicated map values:
List<String> mapValues = new ArrayList<String>(myHashMap.values());
Collections.sort(mapValues);
Good Luck!
http://snipplr.com/view/2789/sorting-map-keys-by-comparing-its-values/
get the keys
List keys = new ArrayList(yourMap.keySet());
Sort them
Collections.sort(keys)
print them.
In any case, you can't have sorted values in HashMap (according to API This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time ].
Though you can push all these values to LinkedHashMap, for later use as well.
Seems like you might want a treemap.
http://docs.oracle.com/javase/7/docs/api/java/util/TreeMap.html
You can pass in a custom comparator to it if that applies.
In Java 8:
Comparator<Entry<String, Item>> valueComparator =
(e1, e2) -> e1.getValue().getField().compareTo(e2.getValue().getField());
Map<String, Item> sortedMap =
unsortedMap.entrySet().stream().
sorted(valueComparator).
collect(Collectors.toMap(Entry::getKey, Entry::getValue,
(e1, e2) -> e1, LinkedHashMap::new));
Using Guava:
Map<String, Item> map = ...;
Function<Item, Integer> getField = new Function<Item, Integer>() {
public Integer apply(Item item) {
return item.getField(); // the field to sort on
}
};
comparatorFunction = Functions.compose(getField, Functions.forMap(map));
comparator = Ordering.natural().onResultOf(comparatorFunction);
Map<String, Item> sortedMap = ImmutableSortedMap.copyOf(map, comparator);
Custom compare function which includes functionality for the Turkish alphabet or other different languages than english.
public <K extends Comparable,V extends Comparable> LinkedHashMap<K,V> sortByKeys(LinkedHashMap<K,V> map){
List<K> keys = new LinkedList<K>(map.keySet());
Collections.sort(keys, (Comparator<? super K>) new Comparator<String>() {
#Override
public int compare(String first, String second) {
Collator collator = Collator.getInstance(Locale.getDefault());
//Collator collator = Collator.getInstance(new Locale("tr", "TR"));
return collator.compare(first, second);
}
});
LinkedHashMap<K,V> sortedMap = new LinkedHashMap<K,V>();
for(K key: keys){
sortedMap.put(key, map.get(key));
}
return sortedMap;
}
here is the using example as the following
LinkedHashMap<String, Boolean> ligList = new LinkedHashMap<String, Boolean>();
ligList = sortByKeys(ligList);
Without any more information, it's hard to know exactly what you want. However, when choosing what data structure to use, you need to take into account what you need it for. Hashmaps are not designed for sorting - they are designed for easy retrieval. So in your case, you'd probably have to extract each element from the hashmap, and put them into a data structure more conducive to sorting, such as a heap or a set, and then sort them there.
If you want to combine a Map for efficient retrieval with a SortedMap, you may use the ConcurrentSkipListMap.
Of course, you need the key to be the value used for sorting.
have you considered using a LinkedHashMap<>()..?
public static void main(String[] args) {
Map<Object, Object> handler = new LinkedHashMap<Object, Object>();
handler.put("item", "Value");
handler.put(2, "Movies");
handler.put("isAlive", true);
for (Map.Entry<Object, Object> entrY : handler.entrySet())
System.out.println(entrY.getKey() + ">>" + entrY.getValue());
List<Map.Entry<String, Integer>> entries = new ArrayList<Map.Entry<String, Integer>>();
Collections.sort(entries, new Comparator<Map.Entry<String, Integer>>() {
public int compare(Map.Entry<String, Integer> a,
Map.Entry<String, Integer> b) {
return a.getValue().compareTo(b.getValue());
}
});
}
results into an organized linked object.
item>>Value
2>>Movies
isAlive>>true
check the sorting part picked from here..
I have developed a class which can be used to sort a map on the basis of keys and values. The basic idea is if you have sort a map using keys then create a TreepMap from your Map which will sort the map by keys. And in case of sorting by values create a list from entrySet and sort the list using comparator interface.
Here is the full solution :
public static void main(String[] args) {
Map<String, Integer> unSortedMap = new LinkedHashMap<String, Integer>();
unSortedMap.put("A", 2);
unSortedMap.put("V", 1);
unSortedMap.put("G", 5);
System.out.println("Unsorted Map :\n");
for (Map.Entry<String, Integer> entry : unSortedMap.entrySet()) {
System.out.println(entry.getKey() + " " + entry.getValue());
}
System.out.println("\n");
System.out.println("Sorting Map Based on Keys :\n");
Map<String, Integer> keySortedMap = new TreeMap<String, Integer>(unSortedMap);
for (Map.Entry<String, Integer> entry : keySortedMap.entrySet()) {
System.out.println(entry.getKey() + " " + entry.getValue());
}
System.out.println("\n");
System.out.println("Sorting Map Based on Values :\n");
List<Entry<String, Integer>> entryList = new ArrayList<Entry<String, Integer>>(unSortedMap.entrySet());
Collections.sort(entryList, new Comparator<Entry<String, Integer>>() {
#Override
public int compare(Entry<String, Integer> obj1, Entry<String, Integer> obj2) {
return obj1.getValue().compareTo(obj2.getValue());
}
});
unSortedMap.clear();
for (Entry<String, Integer> entry : entryList) {
unSortedMap.put(entry.getKey(), entry.getValue());
System.out.println(entry.getKey() + " " + entry.getValue());
}
}
Code is properly tested :D
Sorting HashMap by Value:
As others have pointed out. HashMaps are for easy lookups if you change that or try to sort inside the map itself you will no longer have O(1) lookup.
The code for your sorting is as follows:
class Obj implements Comparable<Obj>{
String key;
ArrayList<Integer> val;
Obj(String key, ArrayList<Integer> val)
{
this.key=key;
this.val=val;
}
public int compareTo(Obj o)
{
/* Write your sorting logic here.
this.val compared to o.val*/
return 0;
}
}
public void sortByValue(Map<String, ArrayList<>> mp){
ArrayList<Obj> arr=new ArrayList<Obj>();
for(String z:mp.keySet())//Make an object and store your map into the arrayList
{
Obj o=new Obj(z,mp.get(z));
arr.add(o);
}
System.out.println(arr);//Unsorted
Collections.sort(arr);// This sorts based on the conditions you coded in the compareTo function.
System.out.println(arr);//Sorted
}
A proper answer.
HashMap<Integer, Object> map = new HashMap<Integer, Object>();
ArrayList<Integer> sortedKeys = new ArrayList<Integer>(map.keySet());
Collections.sort(sortedKeys, new Comparator<Integer>() {
#Override
public int compare(Integer a, Integer b) {
return a.compareTo(b);
}
});
for (Integer key: sortedKeys) {
//map.get(key);
}
Note that HashMap itself cannot maintain sorting, as other answers have pointed out. It's a hash map, and hashed values are unsorted. You can thus either sort the keys when you need to and then access the values in order, as I demonstrated above, or you can find a different collection to store your data, like an ArrayList of Pairs/Tuples, such as the Pair found in Apache Commons:
https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/tuple/Pair.html
Sorting by key:
public static void main(String[] args) {
Map<String,String> map = new HashMap<>();
map.put("b", "dd");
map.put("c", "cc");
map.put("a", "aa");
map = new TreeMap<>(map);
for (String key : map.keySet()) {
System.out.println(key+"="+map.get(key));
}
}
I developed a fully tested working solution. Hope it helps
import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) {
try {
BufferedReader in = new BufferedReader(new java.io.InputStreamReader (System.in));
String str;
HashMap<Integer, Business> hm = new HashMap<Integer, Business>();
Main m = new Main();
while ((str = in.readLine()) != null) {
StringTokenizer st = new StringTokenizer(str);
int id = Integer.parseInt(st.nextToken()); // first integer
int rating = Integer.parseInt(st.nextToken()); // second
Business a = m.new Business(id, rating);
hm.put(id, a);
List<Business> ranking = new ArrayList<Business>(hm.values());
Collections.sort(ranking, new Comparator<Business>() {
public int compare(Business i1, Business i2) {
return i2.getRating() - i1.getRating();
}
});
for (int k=0;k<ranking.size();k++) {
System.out.println((ranking.get(k).getId() + " " + (ranking.get(k)).getRating()));
}
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public class Business{
Integer id;
Integer rating;
public Business(int id2, int rating2)
{
id=id2;
rating=rating2;
}
public Integer getId()
{
return id;
}
public Integer getRating()
{
return rating;
}
}
}
HashMap doesnt maintain any order, so if you want any kind of ordering, you need to store that in something else, which is a map and can have some kind of ordering, like LinkedHashMap
below is a simple program, by which you can sort by key, value, ascending ,descending ..( if you modify the compactor, you can use any kind of ordering, on keys and values)
package com.edge.collection.map;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
public class SortMapByKeyValue {
Map<String, Integer> map = new HashMap<String, Integer>();
public static void main(String[] args) {
SortMapByKeyValue smkv = new SortMapByKeyValue();
smkv.createMap();
System.out.println("After sorting by key ascending order......");
smkv.sortByKey(true);
System.out.println("After sorting by key descindeng order......");
smkv.sortByKey(false);
System.out.println("After sorting by value ascending order......");
smkv.sortByValue(true);
System.out.println("After sorting by value descindeng order......");
smkv.sortByValue(false);
}
void createMap() {
map.put("B", 55);
map.put("A", 80);
map.put("D", 20);
map.put("C", 70);
map.put("AC", 70);
map.put("BC", 70);
System.out.println("Before sorting......");
printMap(map);
}
void sortByValue(boolean order) {
List<Entry<String, Integer>> list = new LinkedList<Entry<String, Integer>>(map.entrySet());
Collections.sort(list, new Comparator<Entry<String, Integer>>() {
public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
if (order) {
return o1.getValue().compareTo(o2.getValue());
} else {
return o2.getValue().compareTo(o1.getValue());
}
}
});
Map<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
for (Entry<String, Integer> entry : list) {
sortedMap.put(entry.getKey(), entry.getValue());
}
printMap(sortedMap);
}
void sortByKey(boolean order) {
List<Entry<String, Integer>> list = new LinkedList<Entry<String, Integer>>(map.entrySet());
Collections.sort(list, new Comparator<Entry<String, Integer>>() {
public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
if (order) {
return o1.getKey().compareTo(o2.getKey());
} else {
return o2.getKey().compareTo(o1.getKey());
}
}
});
Map<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
for (Entry<String, Integer> entry : list) {
sortedMap.put(entry.getKey(), entry.getValue());
}
printMap(sortedMap);
}
public void printMap(Map<String, Integer> map) {
// System.out.println(map);
for (Entry<String, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey() + " : " + entry.getValue());
}
}
}
here is the git link
Convert hashmap to a ArrayList with a pair class
Hashmap<Object,Object> items = new HashMap<>();
to
List<Pair<Object,Object>> items = new ArrayList<>();
so you can sort it as you want, or list sorted by adding order.
Sorting HashMap by value in Java:
public class HashMapSortByValue {
public static void main(String[] args) {
HashMap<Long,String> unsortMap = new HashMap<Long,String>();
unsortMap.put(5l,"B");
unsortMap.put(8l,"A");
unsortMap.put(2l, "D");
unsortMap.put(7l,"C" );
System.out.println("Before sorting......");
System.out.println(unsortMap);
HashMap<Long,String> sortedMapAsc = sortByComparator(unsortMap);
System.out.println("After sorting......");
System.out.println(sortedMapAsc);
}
public static HashMap<Long,String> sortByComparator(
HashMap<Long,String> unsortMap) {
List<Map.Entry<Long,String>> list = new LinkedList<Map.Entry<Long,String>>(
unsortMap.entrySet());
Collections.sort(list, new Comparator<Map.Entry<Long,String>> () {
public int compare(Map.Entry<Long,String> o1, Map.Entry<Long,String> o2) {
return o1.getValue().compareTo(o2.getValue());
}
});
HashMap<Long,String> sortedMap = new LinkedHashMap<Long,String>();
for (Entry<Long,String> entry : list) {
sortedMap.put(entry.getKey(), entry.getValue());
}
return sortedMap;
}
}

How do I put a tree map with keys and values sorted into an ascending list?

So this program gives the occcurences of each word. I need to make a list with this data sorting these words in ascending order.
import java.util.*;
public class A1E5{
public static void main(String[] args) {
// Set text in a string
String text = "Good morning. Have a good class. " +
"Have a good visit. Have fun!";
// Create a TreeMap to hold words as key and count as value
Map<String, Integer> map = new TreeMap<>();
String[] words = text.split("[\\s+\\p{P}]");
for (int i = 0; i < words.length; i++) {
String key = words[i].toLowerCase();
if (key.length() > 0) {
if (!map.containsKey(key)) {
map.put(key, 1);
}
else {
int value = map.get(key);
value++;
map.put(key, value);
}
}
}
// Display key and value for each entry
map.forEach((k, v) -> System.out.println(k + "\t" + v));
}
}
Implement Comparator interface and override its compare method in java.
Obtain map.entrySet() in set, convert it into list (we have converted set to list because Collections’s sort method can accept only list type as parameter).
Call Collections.sort and pass list [i.e. listOfentrySet] as parameter.
Collections.sort internally calls Arrays.sort, Arrays.Sort() internally calls Merge Sort.Merge sort calls overridden compare method of Comparator interface for comparison of keys.Ultimately listOfentrySet will contain entry (key-value) pairs sorted on basis of keys in java.
Its a simple google search but here you are:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
class SortByKeyAscending implements Comparator<Map.Entry<Integer, Integer>>{
#Override
public int compare( Map.Entry<Integer,Integer> entry1, Map.Entry<Integer,Integer> entry2){
return (entry1.getKey()).compareTo( entry2.getKey() );
}
}
public class SortMapByKeyAscendingExample {
public static void main(String...a){
Map<Integer, Integer> map = new LinkedHashMap<Integer, Integer>();
map.put(4, 1);
map.put(2, 1);
map.put(3, 1);
map.put(5, 1);
Set<Entry<Integer, Integer>> entrySet = map.entrySet();
List<Entry<Integer, Integer>> listOfentrySet = new ArrayList<Entry<Integer, Integer>>(entrySet);
System.out.print("Before sorting by key : ");
for(Map.Entry<Integer, Integer> entry:listOfentrySet){
System.out.print(entry.getKey()+"="+entry.getValue()+" ");
}
Collections.sort(listOfentrySet, new SortByKeyAscending());
System.out.print("\nAfter sorting by key(ascending): ");
for(Map.Entry<Integer, Integer> entry:listOfentrySet)
System.out.print(entry.getKey()+"="+entry.getValue()+" ");
}
}
The output would be (key value)
Before sorting : 4=1 2=1 3=1 5=1
After sorting : 2=1 3=1 4=1 5=1
If I understood your requirement correctly, since you can't have a TreeMap itself sort on the values you want something like this:
List<String> wordsList = new ArrayList<String>();
map.forEach((k, v) -> wordsList.add(k));
System.out.println(Arrays.toString(wordsList.toArray()));
Output:
[a, class, fun, good, have, morning, visit]
Or this:
List<String> wordsList = new ArrayList<String>();
for(Map.Entry<String, Integer> entry : map.entrySet()) {
String key = entry.getKey();
for(int i = 0 ; i <= entry.getValue(); i++) {
wordsList.add(key);
}
}
System.out.println(Arrays.toString(wordsList.toArray()));
Output:
[a, a, a, class, class, fun, fun, good, good, good, good, have, have, have, have, morning, morning, visit, visit]
If you're trying to print out the results ordered by count, you can do this:
map.entrySet()
.stream()
.sorted(Map.Entry.comparingByValue())
.forEach(e -> System.out.println(e.getKey() + "\t" + e.getValue()));
You can also use streams to produce your frequency map in the first place:
Pattern.compile("[\\s+\\p{P}]")
.splitAsStream(text)
.map(String::toLowerCase)
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
.entrySet()
.stream()
.sorted(Map.Entry.comparingByValue())
.forEach(e -> System.out.println(e.getKey() + "\t" + e.getValue()));

Java HashMap key value storage and retrieval

I want to store values and retrieve them from a Java HashMap.
This is what I have so far:
public void processHashMap()
{
HashMap hm = new HashMap();
hm.put(1,"godric gryfindor");
hm.put(2,"helga hufflepuff");
hm.put(3,"rowena ravenclaw");
hm.put(4,"salazaar slytherin");
}
I want to retrieve all Keys and Values from the HashMap as a Java Collection or utility set (for example LinkedList).
I know I can get the value if I know the key, like this:
hm.get(1);
Is there a way to retrieve key values as a list?
I use these three ways to iterate a map. All methods (keySet, values, entrySet) return a collection.
// Given the following map
Map<KeyClass, ValueClass> myMap;
// Iterate all keys
for (KeyClass key : myMap.keySet())
System.out.println(key);
// Iterate all values
for (ValueClass value : myMap.values())
System.out.println(value);
// Iterate all key/value pairs
for (Entry<KeyClass, ValueClass> entry : myMap.entrySet())
System.out.println(entry.getKey() + " - " + entry.getValue());
Since Java 8 i often use Streams with lambda expressions.
// Iterate all keys
myMap.keySet().stream().forEach(key -> System.out.println(key));
// Iterate all values
myMap.values().parallelStream().forEach(value -> System.out.println(value));
// Iterate all key/value pairs
myMap.entrySet().stream().forEach(entry -> System.out.println(entry.getKey() + " - " + entry.getValue()));
Java Hashmap key value example:
public void processHashMap() {
//add keys->value pairs to a hashmap:
HashMap hm = new HashMap();
hm.put(1, "godric gryfindor");
hm.put(2, "helga hufflepuff");
hm.put(3, "rowena ravenclaw");
hm.put(4, "salazaar slytherin");
//Then get data back out of it:
LinkedList ll = new LinkedList();
Iterator itr = hm.keySet().iterator();
while(itr.hasNext()) {
String key = itr.next();
ll.add(key);
}
System.out.print(ll); //The key list will be printed.
}
map.keySet() would give you all the keys
//import statements
import java.util.HashMap;
import java.util.Iterator;
import java.util.TreeMap;
// hashmap test class
public class HashMapTest {
public static void main(String args[]) {
HashMap<Integer,String> hashMap = new HashMap<Integer,String>();
hashMap.put(91, "India");
hashMap.put(34, "Spain");
hashMap.put(63, "Philippines");
hashMap.put(41, "Switzerland");
// sorting elements
System.out.println("Unsorted HashMap: " + hashMap);
TreeMap<Integer,String> sortedHashMap = new TreeMap<Integer,String>(hashMap);
System.out.println("Sorted HashMap: " + sortedHashMap);
// hashmap empty check
boolean isHashMapEmpty = hashMap.isEmpty();
System.out.println("HashMap Empty: " + isHashMapEmpty);
// hashmap size
System.out.println("HashMap Size: " + hashMap.size());
// hashmap iteration and printing
Iterator<Integer> keyIterator = hashMap.keySet().iterator();
while(keyIterator.hasNext()) {
Integer key = keyIterator.next();
System.out.println("Code=" + key + " Country=" + hashMap.get(key));
}
// searching element by key and value
System.out.println("Does HashMap contains 91 as key: " + hashMap.containsKey(91));
System.out.println("Does HashMap contains India as value: " + hashMap.containsValue("India"));
// deleting element by key
Integer key = 91;
Object value = hashMap.remove(key);
System.out.println("Following item is removed from HashMap: " + value);
}
}
You can use keySet() to retrieve the keys.
You should also consider adding typing in your Map, e.g :
Map<Integer, String> hm = new HashMap<Integer, String>();
hm.put(1,"godric gryfindor");
hm.put(2,"helga hufflepuff");
hm.put(3,"rowena ravenclaw");
hm.put(4,"salazaar slytherin");
Set<Integer> keys = hm.keySet();
void hashMapExample(){
HashMap<String, String> hMap = new HashMap<String, String>();
hMap.put("key1", "val1");
hMap.put("key2", "val2");
hMap.put("key3", "val3");
hMap.put("key4", "val4");
hMap.put("key5", "val5");
if(hMap != null && !hMap.isEmpty()){
for(String key : hMap.keySet()){
System.out.println(key+":"+hMap.get(key));
}
}
}

sorting a 2d data structure in java

I need to sort a 2d key/value pair by the value. I have read many references about this on the web and have ended up writing my own class to do this using HashMaps(see below). I put the code into a condensed working class that reproduces the problem with the minimum amount of code so that you can just cut and paste it into your IDE for quick diagnostics.
As you can see, the method that I wrote is correctly sorting the values before they are entered into sortedMap. However, for some reason, they values are then again unordered in a different way when I try to subsequently iterate through sortedMap.
Can anyone show me how to fix the code below so that I iterate through a resulting 2D data object that gives me my data in descending order?
EDIT: Re-wrote using TreeMaps, and am still getting a similar problem. Here is the re-written code:
import java.util.*;
public class HashMapDemo {
public static void main(String args[]) {
// Code that creates and populates the unordered HashMap:
TreeMap<Integer, Double> unSortedMap = new TreeMap<Integer, Double>();
unSortedMap.put(1343, 0.521851);
unSortedMap.put(1950, -0.301208);
unSortedMap.put(3667, -0.0280762);
unSortedMap.put(3879, 0.154724);
unSortedMap.put(4124, 0.022583);
// Code that calls the ordering method:
TreeMap<Integer, Double> sortedMap = new TreeMap<Integer, Double>(
sortTreeMap(unSortedMap));
// Code that iterates through the "sorted" hashmap.
System.out.println("now iterate through sortedMap: ");
for (Integer key : sortedMap.keySet()) {
System.out.println("key, sortedMap.get(key) are: " + key + ", "
+ sortedMap.get(key));
}
}
// Code for the ordering method. Note that the println tests indicate that
// this method is correctly sorting the key/value pairs in the hashmap:
private static TreeMap<Integer, Double> sortTreeMap(
TreeMap<Integer, Double> input) {
System.out
.println("input.size() upon entering sortHasMap() function is: "
+ input.size());
int startSize = input.size();
// create a hashmap to store sorted output
TreeMap<Integer, Double> sortedMap = new TreeMap<Integer, Double>();
// repeat the following process once for every key/value pair in the
// hashmap
for (int i = 0; i < startSize; i++) {
int mySize = input.size();
System.out.println("mySize is: " + mySize);
double maxVal = Double.NEGATIVE_INFINITY;
int maxKey = 0;
// iterate through each key in hashmap to find key/value of max
// value
for (Integer key : input.keySet()) {
if (maxVal < input.get(key)) {
maxVal = input.get(key);
maxKey = key;
}
}
// add key/value of max of that iteration to sorted map and remove
// from input before next iteration
sortedMap.put(maxKey, maxVal);
input.remove(maxKey);
System.out.println("sortedMap.put(maxKey, maxVal) are: " + maxKey
+ ", " + maxVal);
}
return sortedMap;
}
}
You need only two lines to achieve what you want. Here are those two lines:
Map<Integer, Double> sortedMap = new TreeMap<Integer, Double>(new Comparator<Integer>() {
public int compare(Integer o1, Integer o2) {
return map.get(o2).compareTo(map.get(o1)); // reverse order of values
}
});
sortedMap.putAll(map);
Here's the complete runnable code:
public static void main(String[] args) {
final Map<Integer, Double> map = new HashMap<Integer, Double>();
map.put(1343, 0.521851);
map.put(1950, -0.301208);
map.put(3667, -0.0280762);
map.put(3879, 0.154724);
map.put(4124, 0.022583);
Map<Integer, Double> sortedMap = sortMap(map);
for (Map.Entry<Integer, Double> entry : sortedMap.entrySet()) {
System.out.println(entry.getKey() + ", " + entry.getValue());
}
}
public static Map<Integer, Double> sortMap(final Map<Integer, Double> map) {
Map<Integer, Double> sortedMap = new TreeMap<Integer, Double>(new Comparator<Integer>() {
public int compare(Integer o1, Integer o2) {
return map.get(o2).compareTo(map.get(o1));
}
});
sortedMap.putAll(map);
return sortedMap;
}
Output:
1343, 0.521851
3879, 0.154724
4124, 0.022583
3667, -0.0280762
1950, -0.301208
Notes: You specify how you want entries ordered in a TreeSet by passing the Comparator you want to use into the constructor. The TreeSet implementation does the rest.
Other notes:
The best way to iterate over the keys/values of a map is by iterating over Map.entrySet()
Always use the abstract type for your variables - eg Map<?, ?> myMap not the concrete implementation (ie HashMap<?, ?> myMap)
Here's the generic version of the sortMap method that will sort any suitable map based on the reverse order of the values:
public static <K, V extends Comparable<V>> Map<K, V> sortMap2(final Map<K, V> map) {
Map<K, V> sortedMap = new TreeMap<K, V>(new Comparator<K>() {
public int compare(K o1, K o2) {
return map.get(o2).compareTo(map.get(o1));
}
});
sortedMap.putAll(map);
return sortedMap;
}
Use a TreeMap. Its a SortedMap that uses the natural ordering of keys. In your case, it will order by the Integer key.
It does the sorting for you.
java.util.HashMap is unordered.
This class makes no guarantees as to the order of the map; in
particular, it does not guarantee that the order will remain constant
over time.
EDIT After reading the question correctly
Use a Comparator for the TreeMap constructor that compares the values.

How to sort a HashMap in Java [duplicate]

This question already has answers here:
Sort a Map<Key, Value> by values
(64 answers)
Closed 3 years ago.
How are we able to sort a HashMap<key, ArrayList>?
I want to sort on the basis of a value in the ArrayList.
Do you have to use a HashMap? If you only need the Map Interface use a TreeMap
If you want to sort by comparing values in the HashMap. You have to write code to do this, if you want to do it once you can sort the values of your HashMap:
Map<String, Person> people = new HashMap<>();
Person jim = new Person("Jim", 25);
Person scott = new Person("Scott", 28);
Person anna = new Person("Anna", 23);
people.put(jim.getName(), jim);
people.put(scott.getName(), scott);
people.put(anna.getName(), anna);
// not yet sorted
List<Person> peopleByAge = new ArrayList<>(people.values());
Collections.sort(peopleByAge, Comparator.comparing(Person::getAge));
for (Person p : peopleByAge) {
System.out.println(p.getName() + "\t" + p.getAge());
}
If you want to access this sorted list often, then you could insert your elements into a HashMap<TreeSet<Person>>, though the semantics of sets and lists are a bit different.
Sorted List by hasmap keys:
SortedSet<String> keys = new TreeSet<String>(myHashMap.keySet());
Sorted List by hashmap values:
SortedSet<String> values = new TreeSet<String>(myHashMap.values());
In case of duplicated map values:
List<String> mapValues = new ArrayList<String>(myHashMap.values());
Collections.sort(mapValues);
Good Luck!
http://snipplr.com/view/2789/sorting-map-keys-by-comparing-its-values/
get the keys
List keys = new ArrayList(yourMap.keySet());
Sort them
Collections.sort(keys)
print them.
In any case, you can't have sorted values in HashMap (according to API This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time ].
Though you can push all these values to LinkedHashMap, for later use as well.
Seems like you might want a treemap.
http://docs.oracle.com/javase/7/docs/api/java/util/TreeMap.html
You can pass in a custom comparator to it if that applies.
In Java 8:
Comparator<Entry<String, Item>> valueComparator =
(e1, e2) -> e1.getValue().getField().compareTo(e2.getValue().getField());
Map<String, Item> sortedMap =
unsortedMap.entrySet().stream().
sorted(valueComparator).
collect(Collectors.toMap(Entry::getKey, Entry::getValue,
(e1, e2) -> e1, LinkedHashMap::new));
Using Guava:
Map<String, Item> map = ...;
Function<Item, Integer> getField = new Function<Item, Integer>() {
public Integer apply(Item item) {
return item.getField(); // the field to sort on
}
};
comparatorFunction = Functions.compose(getField, Functions.forMap(map));
comparator = Ordering.natural().onResultOf(comparatorFunction);
Map<String, Item> sortedMap = ImmutableSortedMap.copyOf(map, comparator);
Custom compare function which includes functionality for the Turkish alphabet or other different languages than english.
public <K extends Comparable,V extends Comparable> LinkedHashMap<K,V> sortByKeys(LinkedHashMap<K,V> map){
List<K> keys = new LinkedList<K>(map.keySet());
Collections.sort(keys, (Comparator<? super K>) new Comparator<String>() {
#Override
public int compare(String first, String second) {
Collator collator = Collator.getInstance(Locale.getDefault());
//Collator collator = Collator.getInstance(new Locale("tr", "TR"));
return collator.compare(first, second);
}
});
LinkedHashMap<K,V> sortedMap = new LinkedHashMap<K,V>();
for(K key: keys){
sortedMap.put(key, map.get(key));
}
return sortedMap;
}
here is the using example as the following
LinkedHashMap<String, Boolean> ligList = new LinkedHashMap<String, Boolean>();
ligList = sortByKeys(ligList);
Without any more information, it's hard to know exactly what you want. However, when choosing what data structure to use, you need to take into account what you need it for. Hashmaps are not designed for sorting - they are designed for easy retrieval. So in your case, you'd probably have to extract each element from the hashmap, and put them into a data structure more conducive to sorting, such as a heap or a set, and then sort them there.
If you want to combine a Map for efficient retrieval with a SortedMap, you may use the ConcurrentSkipListMap.
Of course, you need the key to be the value used for sorting.
have you considered using a LinkedHashMap<>()..?
public static void main(String[] args) {
Map<Object, Object> handler = new LinkedHashMap<Object, Object>();
handler.put("item", "Value");
handler.put(2, "Movies");
handler.put("isAlive", true);
for (Map.Entry<Object, Object> entrY : handler.entrySet())
System.out.println(entrY.getKey() + ">>" + entrY.getValue());
List<Map.Entry<String, Integer>> entries = new ArrayList<Map.Entry<String, Integer>>();
Collections.sort(entries, new Comparator<Map.Entry<String, Integer>>() {
public int compare(Map.Entry<String, Integer> a,
Map.Entry<String, Integer> b) {
return a.getValue().compareTo(b.getValue());
}
});
}
results into an organized linked object.
item>>Value
2>>Movies
isAlive>>true
check the sorting part picked from here..
I have developed a class which can be used to sort a map on the basis of keys and values. The basic idea is if you have sort a map using keys then create a TreepMap from your Map which will sort the map by keys. And in case of sorting by values create a list from entrySet and sort the list using comparator interface.
Here is the full solution :
public static void main(String[] args) {
Map<String, Integer> unSortedMap = new LinkedHashMap<String, Integer>();
unSortedMap.put("A", 2);
unSortedMap.put("V", 1);
unSortedMap.put("G", 5);
System.out.println("Unsorted Map :\n");
for (Map.Entry<String, Integer> entry : unSortedMap.entrySet()) {
System.out.println(entry.getKey() + " " + entry.getValue());
}
System.out.println("\n");
System.out.println("Sorting Map Based on Keys :\n");
Map<String, Integer> keySortedMap = new TreeMap<String, Integer>(unSortedMap);
for (Map.Entry<String, Integer> entry : keySortedMap.entrySet()) {
System.out.println(entry.getKey() + " " + entry.getValue());
}
System.out.println("\n");
System.out.println("Sorting Map Based on Values :\n");
List<Entry<String, Integer>> entryList = new ArrayList<Entry<String, Integer>>(unSortedMap.entrySet());
Collections.sort(entryList, new Comparator<Entry<String, Integer>>() {
#Override
public int compare(Entry<String, Integer> obj1, Entry<String, Integer> obj2) {
return obj1.getValue().compareTo(obj2.getValue());
}
});
unSortedMap.clear();
for (Entry<String, Integer> entry : entryList) {
unSortedMap.put(entry.getKey(), entry.getValue());
System.out.println(entry.getKey() + " " + entry.getValue());
}
}
Code is properly tested :D
Sorting HashMap by Value:
As others have pointed out. HashMaps are for easy lookups if you change that or try to sort inside the map itself you will no longer have O(1) lookup.
The code for your sorting is as follows:
class Obj implements Comparable<Obj>{
String key;
ArrayList<Integer> val;
Obj(String key, ArrayList<Integer> val)
{
this.key=key;
this.val=val;
}
public int compareTo(Obj o)
{
/* Write your sorting logic here.
this.val compared to o.val*/
return 0;
}
}
public void sortByValue(Map<String, ArrayList<>> mp){
ArrayList<Obj> arr=new ArrayList<Obj>();
for(String z:mp.keySet())//Make an object and store your map into the arrayList
{
Obj o=new Obj(z,mp.get(z));
arr.add(o);
}
System.out.println(arr);//Unsorted
Collections.sort(arr);// This sorts based on the conditions you coded in the compareTo function.
System.out.println(arr);//Sorted
}
A proper answer.
HashMap<Integer, Object> map = new HashMap<Integer, Object>();
ArrayList<Integer> sortedKeys = new ArrayList<Integer>(map.keySet());
Collections.sort(sortedKeys, new Comparator<Integer>() {
#Override
public int compare(Integer a, Integer b) {
return a.compareTo(b);
}
});
for (Integer key: sortedKeys) {
//map.get(key);
}
Note that HashMap itself cannot maintain sorting, as other answers have pointed out. It's a hash map, and hashed values are unsorted. You can thus either sort the keys when you need to and then access the values in order, as I demonstrated above, or you can find a different collection to store your data, like an ArrayList of Pairs/Tuples, such as the Pair found in Apache Commons:
https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/tuple/Pair.html
Sorting by key:
public static void main(String[] args) {
Map<String,String> map = new HashMap<>();
map.put("b", "dd");
map.put("c", "cc");
map.put("a", "aa");
map = new TreeMap<>(map);
for (String key : map.keySet()) {
System.out.println(key+"="+map.get(key));
}
}
I developed a fully tested working solution. Hope it helps
import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) {
try {
BufferedReader in = new BufferedReader(new java.io.InputStreamReader (System.in));
String str;
HashMap<Integer, Business> hm = new HashMap<Integer, Business>();
Main m = new Main();
while ((str = in.readLine()) != null) {
StringTokenizer st = new StringTokenizer(str);
int id = Integer.parseInt(st.nextToken()); // first integer
int rating = Integer.parseInt(st.nextToken()); // second
Business a = m.new Business(id, rating);
hm.put(id, a);
List<Business> ranking = new ArrayList<Business>(hm.values());
Collections.sort(ranking, new Comparator<Business>() {
public int compare(Business i1, Business i2) {
return i2.getRating() - i1.getRating();
}
});
for (int k=0;k<ranking.size();k++) {
System.out.println((ranking.get(k).getId() + " " + (ranking.get(k)).getRating()));
}
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public class Business{
Integer id;
Integer rating;
public Business(int id2, int rating2)
{
id=id2;
rating=rating2;
}
public Integer getId()
{
return id;
}
public Integer getRating()
{
return rating;
}
}
}
HashMap doesnt maintain any order, so if you want any kind of ordering, you need to store that in something else, which is a map and can have some kind of ordering, like LinkedHashMap
below is a simple program, by which you can sort by key, value, ascending ,descending ..( if you modify the compactor, you can use any kind of ordering, on keys and values)
package com.edge.collection.map;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
public class SortMapByKeyValue {
Map<String, Integer> map = new HashMap<String, Integer>();
public static void main(String[] args) {
SortMapByKeyValue smkv = new SortMapByKeyValue();
smkv.createMap();
System.out.println("After sorting by key ascending order......");
smkv.sortByKey(true);
System.out.println("After sorting by key descindeng order......");
smkv.sortByKey(false);
System.out.println("After sorting by value ascending order......");
smkv.sortByValue(true);
System.out.println("After sorting by value descindeng order......");
smkv.sortByValue(false);
}
void createMap() {
map.put("B", 55);
map.put("A", 80);
map.put("D", 20);
map.put("C", 70);
map.put("AC", 70);
map.put("BC", 70);
System.out.println("Before sorting......");
printMap(map);
}
void sortByValue(boolean order) {
List<Entry<String, Integer>> list = new LinkedList<Entry<String, Integer>>(map.entrySet());
Collections.sort(list, new Comparator<Entry<String, Integer>>() {
public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
if (order) {
return o1.getValue().compareTo(o2.getValue());
} else {
return o2.getValue().compareTo(o1.getValue());
}
}
});
Map<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
for (Entry<String, Integer> entry : list) {
sortedMap.put(entry.getKey(), entry.getValue());
}
printMap(sortedMap);
}
void sortByKey(boolean order) {
List<Entry<String, Integer>> list = new LinkedList<Entry<String, Integer>>(map.entrySet());
Collections.sort(list, new Comparator<Entry<String, Integer>>() {
public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
if (order) {
return o1.getKey().compareTo(o2.getKey());
} else {
return o2.getKey().compareTo(o1.getKey());
}
}
});
Map<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
for (Entry<String, Integer> entry : list) {
sortedMap.put(entry.getKey(), entry.getValue());
}
printMap(sortedMap);
}
public void printMap(Map<String, Integer> map) {
// System.out.println(map);
for (Entry<String, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey() + " : " + entry.getValue());
}
}
}
here is the git link
Convert hashmap to a ArrayList with a pair class
Hashmap<Object,Object> items = new HashMap<>();
to
List<Pair<Object,Object>> items = new ArrayList<>();
so you can sort it as you want, or list sorted by adding order.
Sorting HashMap by value in Java:
public class HashMapSortByValue {
public static void main(String[] args) {
HashMap<Long,String> unsortMap = new HashMap<Long,String>();
unsortMap.put(5l,"B");
unsortMap.put(8l,"A");
unsortMap.put(2l, "D");
unsortMap.put(7l,"C" );
System.out.println("Before sorting......");
System.out.println(unsortMap);
HashMap<Long,String> sortedMapAsc = sortByComparator(unsortMap);
System.out.println("After sorting......");
System.out.println(sortedMapAsc);
}
public static HashMap<Long,String> sortByComparator(
HashMap<Long,String> unsortMap) {
List<Map.Entry<Long,String>> list = new LinkedList<Map.Entry<Long,String>>(
unsortMap.entrySet());
Collections.sort(list, new Comparator<Map.Entry<Long,String>> () {
public int compare(Map.Entry<Long,String> o1, Map.Entry<Long,String> o2) {
return o1.getValue().compareTo(o2.getValue());
}
});
HashMap<Long,String> sortedMap = new LinkedHashMap<Long,String>();
for (Entry<Long,String> entry : list) {
sortedMap.put(entry.getKey(), entry.getValue());
}
return sortedMap;
}
}

Categories