JAVA mapはkey,valueで比較


import java.util.*;

public class MapSortDemo {

   public static void main(String[] args) {

       Map map = new HashMap<>();

       map.put("1", "4");
       map.put("3", "3");
       map.put("2", "2");
       map.put("4", "1");

       //Map resultMap = sortMapByKey(map);    // Key :1.treemap
       
Map resultMap = sortMapByKey2(map); // key :2.list, ( LinkedHashMap )
      // Map resultMap = sortMapByValue(map); // Value :list,

       
for (Map.Entry entry : resultMap.entrySet()) {
           System.out.println(entry.getKey() + " " + entry.getValue());
       }
   }

   /**
    * TreeMap key
    *
@param map
   
* @return
   
*/
   
public static Map sortMapByKey(Map map) {
       if (map == null || map.isEmpty()) {
           return null;
       }
       //TreeMap key , key , ,
       //Map sortMap = new TreeMap();

       //TreeMap ~ key
       
Map sortMap = new TreeMap(new MapKeyComparator());

       sortMap.putAll(map);

       return sortMap;
   }

   /**
    * list key
    *
@param map
   
* @return
   
*/
   
public static Map sortMapByKey2(Map map) {
       if (map == null || map.isEmpty()) {
           return null;
       }
       List> list = new ArrayList<>(map.entrySet());
       Collections.sort(list,new MapKeyComparator2());

       Map sortMap = new LinkedHashMap<>();
       Iterator> iterable = list.iterator();
       while (iterable.hasNext()){
           Map.Entry tmpEntry = iterable.next();
           sortMap.put(tmpEntry.getKey(),tmpEntry.getValue());
       }

       return sortMap;
   }

   /**
    * List Map value
    *
@param oriMap
   
* @return
   
*/
   
public static Map sortMapByValue(Map oriMap) {
       if (oriMap == null || oriMap.isEmpty()) {
           return null;
       }
       // LinkedHashMap, LinkedHashMap put !
       
Map sortedMap = new LinkedHashMap<>();

       //map.entry map list, list
       
List> entryList = new ArrayList<>(oriMap.entrySet());

       Collections.sort(entryList, new MapValueComparator());

       Iterator> iter = entryList.iterator();
       Map.Entry tmpEntry = null;
       while (iter.hasNext()) {
           tmpEntry = iter.next();
           sortedMap.put(tmpEntry.getKey(), tmpEntry.getValue());
       }
       return sortedMap;
   }

}



class MapKeyComparator implements Comparator {

   @Override
   
public int compare(String str1, String str2) {

       return str2.compareTo(str1);
   }
}


class MapValueComparator implements Comparator> {

   @Override
   
public int compare(Map.Entry me1, Map.Entry me2) {

       return me1.getValue().compareTo(me2.getValue());
   }
}

class MapKeyComparator2 implements Comparator> {

   @Override
   
public int compare(Map.Entry me1, Map.Entry me2) {

       return me1.getKey().compareTo(me2.getKey());
   }
}