MapUtils.java
package com.blogspot.na5cent.utils; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; /** * * @author Redcrow */ public class MapUtils { public static Map sort(Map unsortMap) { List list = new LinkedList(unsortMap.entrySet()); Collections.sort(list, new Comparator() { @Override public int compare(Object object1, Object object2) { Object value1 = ((Map.Entry) (object1)).getValue(); Object value2 = ((Map.Entry) (object2)).getValue(); return ((Comparable) value1).compareTo(value2); } }); Map sortedMap = new LinkedHashMap(); for (Iterator it = list.iterator(); it.hasNext();) { Map.Entry entry = (Map.Entry) it.next(); sortedMap.put(entry.getKey(), entry.getValue()); } return sortedMap; } }example to use
... ... Map<String, String> unsortMonths = new HashMap<String, String>(); unsortMonths.put("มกราคม", "01"); unsortMonths.put("กุมภาพันธ์", "02"); unsortMonths.put("มีนาคม", "03"); unsortMonths.put("เมษายน", "04"); unsortMonths.put("พฤษภาคม", "05"); unsortMonths.put("มิถุนายน", "06"); unsortMonths.put("กรกกฎาคม", "07"); unsortMonths.put("สิงหาคม", "08"); unsortMonths.put("กันยายน", "09"); unsortMonths.put("ตุลาคม", "10"); unsortMonths.put("พศจิกายน", "11"); unsortMonths.put("ธันวาคม", "12"); Map<String, String> sortedMonths = MapUtils.sort(unsortMonths); //********* ... ...
unsort
sorted
Nice article on sort map. Understood the concept. Thanks for sharing.
ตอบลบCheers,
http://www.flowerbrackets.com/sort-hashmap-by-value/