Sorting Map keys in Java Example

Sorting Map keys in Java Example:

Sorting map key can be done simply by changing the treemap to treemap. Which will print the keys in ascending order. In the below program we have tried printing the map key with hashmap, since hashmap

 

HashMap:

HashMap is a type of collection in java to store key/value pairs.

We cannot predict the order of the elements like insertion or ascending etc.

 

TreeMap:
To give the values in ascending order by default.

This map is used mainly when we need to sort anything in ascending/descending order. By default it will sort in ascending order.

If you want treemap to sort in descending order, then you have to use “Collections.reverseOrder()”


Map<String, String> myMap1 = new TreeMap<String, String>(Collections.reverseOrder());

 

 

LinkedHashMap:
Same order as insertion order.

 

 

 

Sorting Map keys in Java Example using TreeMap Sample Program:

We converted the hashmap to treemap then using entrySet(), we printed the values. It prints the map keys in ascending order.

 


package in.javadomain;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;

public class MapKeySorting {
public static void main(String[] args) {
Map<String, String> myMap = new HashMap<String, String>();
myMap.put("Google", "Google");
myMap.put("Javadomain", "Javadomain");
myMap.put("Mochajobs", "Mochajobs");
myMap.put("Fforfriend", "Fforfriend");
myMap.put("Facebook", "Facebook");
myMap.put("Youtube", "Youtube");

for (Entry<String, String> string : myMap.entrySet()) {
System.out.println(string);
}

System.out.println("-------------------------------");

Map<String, String> myMap1 = new TreeMap<String, String>(Collections.reverseOrder());
myMap1.put("Google", "Google");
myMap1.put("Javadomain", "Javadomain");
myMap1.put("Mochajobs", "Mochajobs");
myMap1.put("Fforfriend", "Fforfriend");
myMap1.put("Facebook", "Facebook");
myMap1.put("Youtube", "Youtube");

for (Entry<String, String> string : myMap1.entrySet()) {
System.out.println(string);
}

}
}

 

 

Output:

Google=Google
Mochajobs=Mochajobs
Javadomain=Javadomain
Youtube=Youtube
Fforfriend=Fforfriend
Facebook=Facebook
-------------------------------
Youtube=Youtube
Mochajobs=Mochajobs
Javadomain=Javadomain
Google=Google
Fforfriend=Fforfriend
Facebook=Facebook

 

 

657 total views, 2 views today

About: Mirthbees

Blogger, Innovator, Developer and Enterpreneur. Founder of GuruRecharge, Readymade online recharge script. Lead Developer in Bookrate.in