SortMapKey.java |
package map; import java.util.Comparator; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; import java.util.TreeMap; public class SortMapKey { public static void main(String[] args) { Map<String,String> map = new TreeMap<String,String>(new Comparator<String>() { public int compare(String key1, String key2) { return key2.compareTo(key1); } }); //map.put(null, null); map.put("aa", null); map.put("bb", "123"); map.put("dd", "456"); map.put("cc", "789"); Set<String> keySet = map.keySet(); for (String key : keySet) { System.out.println(key + ":" + map.get(key)); } } }
|
输出结果:
dd:456
cc:789
bb:123
aa:null
SortMapValue.java |
package map; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.TreeMap; publicclass SorMaptValue { publicstaticvoid main(String[] args) { Map<String,Date> hashMap = new HashMap<String, Date>(); Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.DATE, -1); hashMap.put("昨天", calendar.getTime()); calendar.add(Calendar.DATE, 1); hashMap.put("今天", calendar.getTime()); calendar.add(Calendar.DATE, 1); hashMap.put("明天", calendar.getTime()); SortValueComparator svc = new SortValueComparator(hashMap); Map<String,Date> map = new TreeMap<String, Date>(svc); map.putAll(hashMap); Set<String> keySet = map.keySet(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); for (String key : keySet) { System.out.println(key + ":" + sdf.format(hashMap.get(key))); } } } class SortValueComparator implements Comparator<String>{ private Map<String,Date> map ; public SortValueComparator(Map<String,Date> map) { this.map = map; } publicint compare(String o1, String o2) { boolean flag = map.get(o1).before(map.get(o2)); if(flag){ return 1; }else{ return -1; } } }
|
运行结果如下:
明天:2015-02-01
今天:2015-01-31
昨天:2015-01-30
原文地址:http://blog.csdn.net/u022812849/article/details/43340027