Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 6

HashMap Sorting by Keys

In this example we are sorting the HashMap based on the keys using the TreeMap
collection class.
package beginnersbook.com;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
import java.util.Set;
import java.util.Iterator;
public class Details {
public static void main(String[] args) {
HashMap<Integer, String> hmap = new HashMap<Integer, String>();
hmap.put(5, "A");
hmap.put(11, "C");
hmap.put(4, "Z");
hmap.put(77, "Y");
hmap.put(9, "P");
hmap.put(66, "Q");
hmap.put(0, "R");

System.out.println("Before Sorting:");
Set set = hmap.entrySet();
Iterator iterator = set.iterator();
while(iterator.hasNext()) {
Map.Entry me = (Map.Entry)iterator.next();
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
}
Map<Integer, String> map = new TreeMap<Integer, String>(hmap);
System.out.println("After Sorting:");
Set set2 = map.entrySet();
Iterator iterator2 = set2.iterator();
while(iterator2.hasNext()) {
Map.Entry me2 = (Map.Entry)iterator2.next();
System.out.print(me2.getKey() + ": ");
System.out.println(me2.getValue());
}

}
Output:
Before Sorting:
0: R
4: Z
5: A
66: Q
9: P
77: Y
11: C
After Sorting:
0: R

4: Z
5: A
9: P
11: C
66: Q
77: Y
HashMap Sorting by Values
In this example we are sorting HashMap by values using Comparator.
package beginnersbook.com;
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;
import java.util.Set;
public class HMapSortingByvalues {
public static void main(String[] args) {
HashMap<Integer, String> hmap = new HashMap<Integer, String>();
hmap.put(5, "A");
hmap.put(11, "C");
hmap.put(4, "Z");
hmap.put(77, "Y");
hmap.put(9, "P");
hmap.put(66, "Q");
hmap.put(0, "R");
System.out.println("Before Sorting:");
Set set = hmap.entrySet();
Iterator iterator = set.iterator();
while(iterator.hasNext()) {
Map.Entry me = (Map.Entry)iterator.next();
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
}
Map<Integer, String> map = sortByValues(hmap);
System.out.println("After Sorting:");
Set set2 = map.entrySet();
Iterator iterator2 = set2.iterator();
while(iterator2.hasNext()) {
Map.Entry me2 = (Map.Entry)iterator2.next();
System.out.print(me2.getKey() + ": ");
System.out.println(me2.getValue());
}
}
private static HashMap sortByValues(HashMap map) {
List list = new LinkedList(map.entrySet());
// Defined Custom Comparator here
Collections.sort(list, new Comparator() {
public int compare(Object o1, Object o2) {
return ((Comparable) ((Map.Entry) (o1)).getValue())
.compareTo(((Map.Entry) (o2)).getValue());
}

});

// Here I am copying the sorted list in HashMap


// using LinkedHashMap to preserve the insertion order
HashMap sortedHashMap = new LinkedHashMap();
for (Iterator it = list.iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry) it.next();
sortedHashMap.put(entry.getKey(), entry.getValue());
}
return sortedHashMap;

}
Output:
Before Sorting:
0: R
4: Z
5: A
66: Q
9: P
77: Y
11: C
After Sorting:
5: A
11: C
9: P
66: Q
0: R
77: Y
4: Z

// Sorting by using key for hashmap


import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
/**
*
* Java Program of sorting Map by keys in Java.
* You can use this technique to sort HashMap,
* Hashtable, ConcurrentHashMap, LinkedHashMap or
* any arbitrary implementation of Map interface in Java.
*

* @author Javin Paul


*/
public class MapSorterDemo{
public static void main(String args[]) {
// Unsorted Integer to String Map
Map<Integer, String> idToName = new HashMap<>();
idToName.put(1001, "Joe");
idToName.put(1003, "Kevin");
idToName.put(1002, "Peter");
idToName.put(1005, "Johnson");
idToName.put(1004, "Ian");
System.out.println("unsorted map : " + idToName);
// Sorting Map by keys
TreeMap<Integer, String> sorted = new TreeMap<>(idToName);
System.out.println("sorted map : " + sorted);
// If you want to process Map in sorted order of keys
// then you can keep an unsorted Map, but take the
// keyset and sort them, before processing
Set<Integer> ids = idToName.keySet();
System.out.println("unsorted keys of map : " + ids);
List<Integer> sortedIds = new ArrayList<>(ids);
Collections.sort(sortedIds);
System.out.println("sorted keys of map : " + sortedIds);
}
}
Output:
unsorted map : {1001=Joe, 1003=Kevin, 1002=Peter, 1005=Johnson,
1004=Ian}
sorted map : {1001=Joe, 1002=Peter, 1003=Kevin, 1004=Ian, 1005=Johnson}
unsorted keys of map : [1001, 1003, 1002, 1005, 1004]
sorted keys of map : [1001, 1002, 1003, 1004, 1005]

import
import
import
import
import
import
import
import

java.util.ArrayList;
java.util.Collections;
java.util.Comparator;
java.util.HashMap;
java.util.List;
java.util.Map;
java.util.Map.Entry;
java.util.Set;

class SortByValue implements Comparator<Map.Entry<Integer, Integer>> {


@Override
public int compare( Map.Entry<Integer,Integer> entry1, Map.Entry<Integer,Integer> entry2){

return (entry1.getValue()).compareTo( entry2.getValue() );


}
}

/**
* @author AnkitMittal
* Copyright (c), AnkitMittal JavaMadeSoEasy.com
* Main class
*/
public class SortMapByValueAscending {
public static void main(String...a){
Mapx<Integer, Integer> map = new HashMap<Integer, Integer>();
map.put(1, 2);
map.put(2, 1);
map.put(3, 9);
map.put(4, 8);
Set<Entry<Integer, Integer>> entrySet = map.entrySet();
List<Entry<Integer, Integer>> listOfentrySet = new ArrayList<Entry<Integer, Integer>>(entrySet);
System.out.print("Before sorting by value: ");
for(Map.Entry<Integer, Integer> entry:listOfentrySet){
System.out.print(entry.getKey()+"="+entry.getValue()+" ");
}
Collections.sort(listOfentrySet, new SortByValue());
System.out.print("\nAfter sorting by value(ascending): ");
for(Map.Entry<Integer, Integer> entry:listOfentrySet)
System.out.print(entry.getKey()+"="+entry.getValue()+" ");
}
}
/*OUTPUT
Before sorting by value: 1=2 2=1 3=9 4=8
After sorting by value(ascending): 2=1 1=2 4=8 3=9
*/

import
import
import
import

java.util.HashMap;
java.util.Iterator;
java.util.Map;
java.util.Set;

public class MapDemo


{
public static void main(String args[])
{
Map map = new HashMap();

//Adding values to the HashMap


map.put("test key 1", "test value 1");
map.put("test key 2", "test value 2");
map.put("test key 3", "test value 3");
System.out.println("Retrieving values from HashMap");
retrieveValuesFromListMethod(map);
System.out.println("**********************\n\n");

}
/*This method retrieves values from Map
*/
public static void retrieveValuesFromListMethod(Map map)
{
Set keys = map.keySet();
Iterator itr = keys.iterator();
String key;
String value;
while(itr.hasNext())
{
key = (String)itr.next();
value = (String)map.get(key);
System.out.println(key + " - "+ value);
}
}

You might also like