Java Sort Map Complete Example

Home / Java Sort Map Complete Example

In this example, we learn how to sort Map in java8. . We can sort map by key and sort map by value as well in java. Let’s take an example we have a hash map that has data of the Movies

For Example Movie name is the key of hash map and movie ratings as the value in hash map. So Now we have many scenerio that we can sort this hash map.

Below are the Scenarios to sort the Hash Map in java.

Now we have seen all the scenarios. So take an example of a hash map that contains the movie name as the key. and rating as values.

Our hash map will look like below:

Map<String, Double> ratingMap = new HashMap<>();
ratingMap.put("Inception", 2.0);
ratingMap.put("GoodFellas", 3.0);
ratingMap.put("Thor", 4.5);
ratingMap.put("Alien", 5.0);
ratingMap.put("Joker ", 1.5);

Now we will sort this map on the basis of above scenerios:

Sort Map by key Alphabetically

In Our case we have movie’s name as keys. So after sorting this map we will get all the movies in ascending order.

HashMap<String, Object> sortAlphabat = ratingMap.entrySet().stream()
				.sorted(Map.Entry.comparingByKey(Comparator.naturalOrder().toString().CASE_INSENSITIVE_ORDER))
				.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue,
						LinkedHashMap::new));

Sort Map by Key Alphabetically In Descending order

HashMap<String, Object> sortAlphabatDesc = ratingMap.entrySet().stream()
                .sorted(Map.Entry.comparingByKey(Comparator.reverseOrder()))
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue,
LinkedHashMap::new));

Sort Map by value in ascending order

In our case, we have ratings as hash map values. So after Sort, we will get the result in ascending order on the basis of ratings.

HashMap<String, Object> sortByValueInAscd = ratingMap.entrySet().stream()
				.sorted(Map.Entry.comparingByValue(Comparator.naturalOrder())).collect(Collectors.toMap(
						Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue, LinkedHashMap::new));

Sort Map by value in descending order

Now we sort the ratings in the descending orders. So the movie that has the highest rating will come first and so on.

HashMap<String, Object> sortByValueInReverse = ratingMap.entrySet().stream()
				.sorted(Map.Entry.comparingByValue(Comparator.reverseOrder())).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue, LinkedHashMap::new));

Sometimes we need to sort our map on the basis of some custom sequence. So for example we have a custom list in which we define the rating sequence and we want to sort the map by this custom list. So for this look at the below example.

List<Double> ratinCustomSeq = Arrays.asList(5.0, 2.0, 3.0, 1.5, 4.5);

HashMap<String, Object> sortByCustomSeq = ratingMap.entrySet().stream()
				.sorted(Map.Entry.comparingByValue(Comparator.comparingInt(ratinCustomSeq::indexOf)))
				.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue,LinkedHashMap::new));

What if you need only the movie’s name on the basis of rating ascending order. So for that, we can return the List of movies instead of the hash map after sorting the map. Look at the below example.

Sort Map by values and Return List of keys

List<String> sortByValueAndGetListOfKeys = ratingMap.entrySet().stream()
				.sorted(Comparator.comparing(Map.Entry::getValue)).map(Map.Entry::getKey).collect(Collectors.toList());

So we have cover all the scenerio for sort hash map so your complete class will look like:

package map;

import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class MapSortDemo {
	public static void main(String[] args) {
		Map<String, Double> ratingMap = new HashMap<>();
		ratingMap.put("Inception", 2.0);
		ratingMap.put("GoodFellas", 3.0);
		ratingMap.put("Thor", 4.5);
		ratingMap.put("Alien", 5.0);
		ratingMap.put("Joker ", 1.5);
		
		HashMap<String, Object> sortAlphabat = ratingMap.entrySet().stream()
                .sorted(Map.Entry.comparingByKey(Comparator.naturalOrder().toString().CASE_INSENSITIVE_ORDER))
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue,
                        LinkedHashMap::new));
		
		System.out.println("Sort map by key Alphabetically Ascending Order => "+ sortAlphabat);
		
		HashMap<String, Object> sortAlphabatDesc = ratingMap.entrySet().stream()
                .sorted(Map.Entry.comparingByKey(Comparator.reverseOrder()))
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue,
                        LinkedHashMap::new));
		
		System.out.println("Sort map by key Alphabetically Descending order=> "+ sortAlphabatDesc);
		
		HashMap<String, Object> sortByValueInAscd = ratingMap.entrySet().stream()
                .sorted(Map.Entry.comparingByValue(Comparator.naturalOrder())).collect(Collectors.toMap(
                        Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue, LinkedHashMap::new));
		
		System.out.println("Sort map by value in Ascending Order => "+ sortByValueInAscd);
		
		HashMap<String, Object> sortByValueInReverse = ratingMap.entrySet().stream()
                .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder())).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue, LinkedHashMap::new));

		System.out.println("Sort map by value in Descending Order => "+ sortByValueInReverse);
		
		List<Double> ratinCustomSeq = Arrays.asList(5.0, 2.0, 3.0, 1.5, 4.5);
		 
		HashMap<String, Object> sortByCustomSeq = ratingMap.entrySet().stream()
		                .sorted(Map.Entry.comparingByValue(Comparator.comparingInt(ratinCustomSeq::indexOf)))
		                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue,LinkedHashMap::new));
		
		System.out.println("Sort map by custom sequence => "+ sortByCustomSeq);
		
		List<String> sortByValueAndGetListOfKeys = ratingMap.entrySet().stream()
                .sorted(Comparator.comparing(Map.Entry::getValue)).map(Map.Entry::getKey).collect(Collectors.toList());

		System.out.println("Only Movies name after sort by rating values in Ascending order => "+ sortByValueAndGetListOfKeys);
	}
}

Output

java sort map by key

You may also like

Send SMS on any mobile number worldwide using Twilio and Spring boot.

Why you should avoid split() method and use splitAsStrem() method of java8

Parse any json using JsonParser.

Like our facebook page

Help Others, Please Share

About Author

Leave a Reply

Your email address will not be published. Required fields are marked *

x