0% found this document useful (0 votes)
67 views6 pages

Sorting Hashmap

This document provides examples of sorting HashMaps by keys and values in Java. It demonstrates using a TreeMap to sort a HashMap by keys. It also shows how to sort a HashMap by values using a custom Comparator and retaining the insertion order using a LinkedHashMap. Finally, it includes additional examples of sorting a HashMap by keys and values in different ways.

Uploaded by

chaitu215
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
67 views6 pages

Sorting Hashmap

This document provides examples of sorting HashMaps by keys and values in Java. It demonstrates using a TreeMap to sort a HashMap by keys. It also shows how to sort a HashMap by values using a custom Comparator and retaining the insertion order using a LinkedHashMap. Finally, it includes additional examples of sorting a HashMap by keys and values in different ways.

Uploaded by

chaitu215
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

HashMap Sorting by Keys

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

[Link]("Before Sorting:");
Set set = [Link]();
Iterator iterator = [Link]();
while([Link]()) {
[Link] me = ([Link])[Link]();
[Link]([Link]() + ": ");
[Link]([Link]());
}
Map<Integer, String> map = new TreeMap<Integer, String>(hmap);
[Link]("After Sorting:");
Set set2 = [Link]();
Iterator iterator2 = [Link]();
while([Link]()) {
[Link] me2 = ([Link])[Link]();
[Link]([Link]() + ": ");
[Link]([Link]());
}

}
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 [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class HMapSortingByvalues {
public static void main(String[] args) {
HashMap<Integer, String> hmap = new HashMap<Integer, String>();
[Link](5, "A");
[Link](11, "C");
[Link](4, "Z");
[Link](77, "Y");
[Link](9, "P");
[Link](66, "Q");
[Link](0, "R");
[Link]("Before Sorting:");
Set set = [Link]();
Iterator iterator = [Link]();
while([Link]()) {
[Link] me = ([Link])[Link]();
[Link]([Link]() + ": ");
[Link]([Link]());
}
Map<Integer, String> map = sortByValues(hmap);
[Link]("After Sorting:");
Set set2 = [Link]();
Iterator iterator2 = [Link]();
while([Link]()) {
[Link] me2 = ([Link])[Link]();
[Link]([Link]() + ": ");
[Link]([Link]());
}
}
private static HashMap sortByValues(HashMap map) {
List list = new LinkedList([Link]());
// Defined Custom Comparator here
[Link](list, new Comparator() {
public int compare(Object o1, Object o2) {
return ((Comparable) (([Link]) (o1)).getValue())
.compareTo((([Link]) (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 = [Link](); [Link]();) {
[Link] entry = ([Link]) [Link]();
[Link]([Link](), [Link]());
}
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 [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
/**
*
* 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<>();
[Link](1001, "Joe");
[Link](1003, "Kevin");
[Link](1002, "Peter");
[Link](1005, "Johnson");
[Link](1004, "Ian");
[Link]("unsorted map : " + idToName);
// Sorting Map by keys
TreeMap<Integer, String> sorted = new TreeMap<>(idToName);
[Link]("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 = [Link]();
[Link]("unsorted keys of map : " + ids);
List<Integer> sortedIds = new ArrayList<>(ids);
[Link](sortedIds);
[Link]("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

[Link];
[Link];
[Link];
[Link];
[Link];
[Link];
[Link];
[Link];

class SortByValue implements Comparator<[Link]<Integer, Integer>> {


@Override
public int compare( [Link]<Integer,Integer> entry1, [Link]<Integer,Integer> entry2){

return ([Link]()).compareTo( [Link]() );


}
}

/**
* @author AnkitMittal
* Copyright (c), AnkitMittal [Link]
* Main class
*/
public class SortMapByValueAscending {
public static void main(String...a){
Mapx<Integer, Integer> map = new HashMap<Integer, Integer>();
[Link](1, 2);
[Link](2, 1);
[Link](3, 9);
[Link](4, 8);
Set<Entry<Integer, Integer>> entrySet = [Link]();
List<Entry<Integer, Integer>> listOfentrySet = new ArrayList<Entry<Integer, Integer>>(entrySet);
[Link]("Before sorting by value: ");
for([Link]<Integer, Integer> entry:listOfentrySet){
[Link]([Link]()+"="+[Link]()+" ");
}
[Link](listOfentrySet, new SortByValue());
[Link]("\nAfter sorting by value(ascending): ");
for([Link]<Integer, Integer> entry:listOfentrySet)
[Link]([Link]()+"="+[Link]()+" ");
}
}
/*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

[Link];
[Link];
[Link];
[Link];

public class MapDemo


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

//Adding values to the HashMap


[Link]("test key 1", "test value 1");
[Link]("test key 2", "test value 2");
[Link]("test key 3", "test value 3");
[Link]("Retrieving values from HashMap");
retrieveValuesFromListMethod(map);
[Link]("**********************\n\n");

}
/*This method retrieves values from Map
*/
public static void retrieveValuesFromListMethod(Map map)
{
Set keys = [Link]();
Iterator itr = [Link]();
String key;
String value;
while([Link]())
{
key = (String)[Link]();
value = (String)[Link](key);
[Link](key + " - "+ value);
}
}

You might also like