Site icon

Sort HashMap by keys in java (ascending & descending order)

What is HashMap in java?

Program – sort HashMap by keys in ascending & descending order

package org.learn.collection.map.hmap;

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

public class SortElementInArrayList {

	public static void main(String[] args) {
		Map<String, String> mapSportsPersonality = new HashMap<>();
		mapSportsPersonality.put("Tennis", "Federer");
		mapSportsPersonality.put("Cricket", "Bradman");
		mapSportsPersonality.put("Basketball", "Jordan");
		mapSportsPersonality.put("Golf", "Woods");
		mapSportsPersonality.put("Boxer", "Ali");

		System.out.println("Demo of sort methods: ");
		demoSortMethod(mapSportsPersonality);		
	}	

	private static void demoSortMethod(Map<String, String> mapSportsPersonality) {
		// {Tennis=Federer, Cricket=Bradman, Golf=Woods, Basketball=Jordan, Boxer=Ali}
		System.out.println("Orignal HashMap:" + mapSportsPersonality);
		
		System.out.println("\n1. Sort HashMap by ascending keys: " );
		TreeMap<String,String>mapSorted = new TreeMap<>(mapSportsPersonality);
		mapSorted.forEach((key, value) -> {
			System.out.println(key + ", " + value);
		});
		
		System.out.println("\n2. Sort HashMap by descending keys: " );
		mapSorted.descendingMap().forEach((key, value) -> {
			System.out.println( key + ", "  + value);
		});		
	}	
}

Output – Sort HashMap in ascending & descending order

Demo of sort methods: 
Orignal HashMap:{Tennis=Federer, Cricket=Bradman, Golf=Woods, Basketball=Jordan, Boxer=Ali}

1. Sort HashMap by ascending keys: 
Basketball, Jordan
Boxer, Ali
Cricket, Bradman
Golf, Woods
Tennis, Federer

2. Sort HashMap by descending keys: 
Tennis, Federer
Golf, Woods
Cricket, Bradman
Boxer, Ali
Basketball, Jordan
Exit mobile version