Add order map by values to utilities
authorMathieu Baudier <mbaudier@argeo.org>
Wed, 20 Sep 2023 07:35:53 +0000 (09:35 +0200)
committerMathieu Baudier <mbaudier@argeo.org>
Wed, 20 Sep 2023 07:35:53 +0000 (09:35 +0200)
org.argeo.cms/src/org/argeo/cms/util/LangUtils.java

index 0e214271d7a612642b35e0af3f1b971a56f89280..e4cc607d666c2777c94680222c5abcb4f1476421 100644 (file)
@@ -12,13 +12,17 @@ import java.time.temporal.ChronoUnit;
 import java.time.temporal.Temporal;
 import java.util.ArrayList;
 import java.util.Collection;
+import java.util.Collections;
+import java.util.Comparator;
 import java.util.Dictionary;
 import java.util.Enumeration;
 import java.util.HashMap;
 import java.util.Hashtable;
 import java.util.Iterator;
+import java.util.LinkedHashMap;
 import java.util.List;
 import java.util.Map;
+import java.util.Map.Entry;
 import java.util.Properties;
 
 import javax.naming.InvalidNameException;
@@ -279,6 +283,24 @@ public class LangUtils {
                throw new IllegalArgumentException("Index " + index + " is not available (size is " + i + ")");
        }
 
+       public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map) {
+               return sortByValue(map, false);
+       }
+
+       public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map, boolean descending) {
+               List<Entry<K, V>> list = new ArrayList<>(map.entrySet());
+               list.sort(Entry.comparingByValue());
+               if (descending)
+                       Collections.reverse(list);
+
+               Map<K, V> result = new LinkedHashMap<>();
+               for (Entry<K, V> entry : list) {
+                       result.put(entry.getKey(), entry.getValue());
+               }
+
+               return result;
+       }
+
        /*
         * EXCEPTIONS
         */