web123456

Correct pose for Java Map sorting by value

Author: Senior Ming Ruyue, CSDN blog expert, senior Java engineer of Ant Group, author of "Performance Optimization Methodology", columnist of "Unlocking Big Factory Thinking: Analyzing Alibaba Java Development Manual", and "Learning Classics Again: Exclusive Analysis of "Effective Java".

Recommended popular articles
(1)"Will software engineers be replaced in the era of artificial intelligence? 》
(2)"Super-full artificial intelligence AI tool navigation website collection"
(3)"How to Write a High Quality Article: From Strategy to Tactics"
(4)"What? Haven't used Cursor? Introduction to the installation and use of intelligent AI code generation tool Cursor
(5)My Performance Methodology
(6)"A Collection of AI Tools Without Magic"

In actual business development, you may encounter the need to sort Java Map by value.

Common ideas for sorting Java Map by value are

1. Put the entry in the map into List

2. Sort the entry in List by value through comparator

3. Put the sorted entry into linkedhashmap

Java 8 uses Stream

import ;
 import ;
 import ;
 import ;

 import static ;
 import static ;

 public class SortTest {

     public static void main(String[] args) throws Exception {

         // Create a map with a string Key and a number value
         Map<String, Integer> budget = new HashMap<>();
         ("clothes", 120);
         ("grocery", 150);
         ("transportation", 100);
         ("utility", 130);
         ("rent", 1150);
         ("miscellneous", 90);
         ("Before sorting: " + budget);

         // Sort by value Ascending order
         Map<String, Integer> sorted = budget
                 .entrySet()
                 .stream()
                 .sorted(comparingByValue())
                 .collect(
                         toMap(::getKey, ::getValue, (e1, e2) -> e2,
                                 LinkedHashMap::new));

         ("Map sorted by value in ascending order: " + sorted);

         // Sort by value descending order
         sorted = budget
                 .entrySet()
                 .stream()
                 .sorted((comparingByValue()))
                 .collect(
                         toMap(::getKey, ::getValue, (e1, e2) -> e2,
                                 LinkedHashMap::new));

         ("Map sorted by value in descending order: " + sorted);
     }


 }

Can be encapsulated into tool classes

/**
  * Map sorting tool class
  *
  * @author liuwangyanghdu@ Mingming like the moon
  */
 public class MapSortUtil {
    
     private static Comparator<> comparatorByKeyAsc = ( o1, o2) -> {
         if (() instanceof Comparable) {
             return ((Comparable) ()).compareTo(());
         }
         throw new UnsupportedOperationException("The key type has not implemented the Comparable interface");
     };


     private static Comparator<> comparatorByKeyDesc = ( o1, o2) -> {
         if (() instanceof Comparable) {
             return ((Comparable) ()).compareTo(());
         }
         throw new UnsupportedOperationException("The key type has not implemented the Comparable interface");
     };


     private static Comparator<> comparatorByValueAsc = ( o1, o2) -> {
         if (() instanceof Comparable) {
             return ((Comparable) ()).compareTo(());
         }
         throw new UnsupportedOperationException("The type of value has not yet implemented the Comparable interface");
     };


     private static Comparator<> comparatorByValueDesc = ( o1, o2) -> {
         if (() instanceof Comparable) {
             return ((Comparable) ()).compareTo(());
         }
         throw new UnsupportedOperationException("The type of value has not yet implemented the Comparable interface");
     };

     /**
      * Ascending order of keys
      */
     public static <K, V> Map<K, V> sortByKeyAsc(Map<K, V> originMap) {
         if (originMap == null) {
             return null;
         }
         return sort(originMap, comparatorByKeyAsc);
     }

     /**
      * keys in descending order
      */
     public static <K, V> Map<K, V> sortByKeyDesc(Map<K, V> originMap) {
         if (originMap == null) {
             return null;
         }
         return sort(originMap, comparatorByKeyDesc);
     }


     /**
      * Sort by ascending order of value
      */
     public static <K, V> Map<K, V> sortByValueAsc(Map<K, V> originMap) {
         if (originMap == null) {
             return null;
         }
         return sort(originMap, comparatorByValueAsc);
     }

     /**
      *Sorted by descending order of values
      */
     public static <K, V> Map<K, V> sortByValueDesc(Map<K, V> originMap) {
         if (originMap == null) {
             return null;
         }
         return sort(originMap, comparatorByValueDesc);
     }

     private static <K, V> Map<K, V> sort(Map<K, V> originMap, Comparator<> comparator) {
         Return ()
                 .stream()
                 .sorted(comparator)
                 .collect(
                         (::getKey, ::getValue, (e1, e2) -> e2,
                                 LinkedHashMap::new));
     }

 }

Test class

package ;

 import ;
 import ;
 import ;

 import ;
 import ;


 /**
  * Map sorting tool class
  *
  * @author liuwangyanghdu@ Mingming like the moon
  */
 @TestInstance(.PER_CLASS)
 class MapSortUtilTest {
     // Create a map with a string Key and a number value
     Map<String, Integer> budget = new HashMap<>();

     @BeforeAll
     public void init() {
         ("clothes", 120);
         ("grocery", 150);
         ("transportation", 100);
         ("utility", 130);
         ("rent", 1150);
         ("miscellneous", 90);
         ("Before sorting: " + budget);
     }

     @Test
     void sortByKeyAsc() {
         ("Key ascending order" + (budget));
     }

     @Test
     void sortByKeyDesc() {
         ("Down key" + (budget));
     }

     @Test
     void sortByValueAsc() {
         ("Ascending order by value" + (budget));
     }

     @Test
     void sortByValueDesc() {
         ("Downward order by value" + (budget));
     }
 }

Java 7 version

import .*;
 import .*;

 public class GFG {

	 // hashmap sorted by value
	 public static HashMap<String, Integer> sortByValue(HashMap<String, Integer> hm)
	 {
		 // Put the entry of HashMap into List
		 List<<String, Integer> > list =
			 new LinkedList<<String, Integer> >(());

		 // Sort List by entry's value
		 (list, new Comparator<<String, Integer> >() {
			 public int compare(<String, Integer> o1,
							 <String, Integer> o2)
			 {
				 return (()).compareTo(());
			 }
		 });
		
		 // Put the sorted elements into LinkedHashMap
		 HashMap<String, Integer> temp = new LinkedHashMap<String, Integer>();
		 for (<String, Integer> aa : list) {
			 ((), ());
		 }
		 return temp;
	 }

	
	 public static void main(String[] args)
	 {

		 HashMap<String, Integer> hm = new HashMap<String, Integer>();

		 // Fill in test data
		 ("Math", 98);
		 ("Data Structure", 85);
		 ("Database", 91);
		 ("Java", 95);
		 ("Operating System", 79);
		 ("Networking", 80);
		 Map<String, Integer> hm1 = sortByValue(hm);

		 // Print data sorted by value
		 for (<String, Integer> en : ()) {
			 ("Key = " + () +
						 ", Value = " + ());
		 }
	 }
 }

Reference article:

1、 Java 8 – Sorting HashMap by values in ascending and descending order

2、 Sort a Map by values

3、Sorting a Hashmap according to values

If the article is helpful to you, please like and follow me. Your encouragement is my greatest motivation for creation! !