package com.guogf.tigger.Map;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
public class TestMapSort {
public static void main(String[] args) {
testHashMap();
testTreeMap1();
testTreeMap2();
testLinkHashMap();
}
public static void testHashMap(){
Map<String, String> map = new HashMap<String, String>();
map.put("1", "Level 1");
map.put("2", "Level 2");
map.put("3", "Level 3");
map.put("a", "Level a");
map.put("b", "Level b");
map.put("c", "Level c");
Iterator<Entry<String, String>> it = map.entrySet().iterator();
while (it.hasNext()) {
Entry<String, String> e = it.next();
System.out.println("testHashMap===>Key: " + e.getKey() + "; Value: " + e.getValue());
}
}
//TreeMap如不指定排序器,默认将按照key值进行升序排序,如果指定了排序器,则按照指定的排序器进行排序。
public static void testTreeMap1(){
Map<String, String> map = new TreeMap<String, String>();
map.put("1", "Level 1");
map.put("3", "Level 3");
map.put("2", "Level 2");
map.put("a", "Level a");
map.put("b", "Level b");
map.put("c", "Level c");
Iterator<Entry<String, String>> it = map.entrySet().iterator();
while (it.hasNext()) {
Entry<String, String> e = it.next();
System.out.println("testTreeMap1===>Key: " + e.getKey() + "; Value: " + e.getValue());
}
}
//TreeMap指定排序器,
public static void testTreeMap2(){
TreeMap<String, String> treeMap2 = new TreeMap<String, String>(new Comparator<String>(){
/*
* int compare(Object o1, Object o2) 返回一个基本类型的整型,
* 返回负数表示:o1 小于o2,
* 返回0 表示:o1和o2相等,
* 返回正数表示:o1大于o2。
*/
public int compare(String o1, String o2) {
//指定排序器按照降序排列
return o2.compareTo(o1);
}
});
treeMap2.put("1", "Level 1");
treeMap2.put("3", "Level 3");
treeMap2.put("2", "Level 2");
treeMap2.put("a", "Level a");
treeMap2.put("b", "Level b");
treeMap2.put("c", "Level c");
Iterator<Entry<String, String>> it =treeMap2.entrySet().iterator();
while (it.hasNext()) {
Entry<String, String> e = it.next();
System.out.println("testTreeMap2===>Key: " + e.getKey() + "; Value: " + e.getValue());
}
}
//LinkedHashMap 根据输入顺序输出
public static void testLinkHashMap(){
Map<String, String> map = new LinkedHashMap<String, String>();
map.put("1", "Level 1");
map.put("5", "Level 3");
map.put("4", "Level 2");
map.put("6", "Level a");
map.put("2", "Level b");
map.put("c", "Level c");
Iterator<Entry<String, String>> it = map.entrySet().iterator();
while (it.hasNext()) {
Entry<String, String> e = it.next();
System.out.println("LinkedHashMap===>Key: " + e.getKey() + "; Value: " + e.getValue());
}
}
}