经常用HashMap用习惯了,一用到Map就想用HashMap但是HashMap并不能胜任一切场景。
第一个场景:排序(参考了网上的代码)
开始的时候我想用HashMap做排序代码如下:
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("d", 2);
map.put("c", 1);
map.put("b", 1);
map.put("a", 3);
List<Map.Entry<String, Integer>> infoIds =
new ArrayList<Map.Entry<String, Integer>>(map.entrySet());
//排序前
for (int i = 0; i < infoIds.size(); i++) {
String id = infoIds.get(i).toString();
System.out.println(id);
}
//d 2
//c 1
//b 1
//a 3
//排序
Collections.sort(infoIds, new Comparator<Map.Entry<String, Integer>>() {
public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
//return (o2.getValue() - o1.getValue());
return (o1.getKey()).toString().compareTo(o2.getKey());
}
});
//排序后
for (int i = 0; i < infoIds.size(); i++) {
String id = infoIds.get(i).toString();
System.out.println(id);
}
//根据key排序
//a 3
//b 1
//c 1
//d 2
//根据value排序
//a 3
//d 2
//b 1
//c 1
但是呢其实Java早就给我们提供好了基于红黑树的TreeMap数据结构,按升序排列
TreeMap<String,String> map=new TreeMap<String, String>();
map.put("body", "aabbc");
map.put("mch_create_ip", "127.0.0.1");
map.put("mch_id", "7551000001");
map.put("nonce_str", "adf880d5c8986bd0deb6423c92c9d948");
map.put("notify_url", "https://wap.tenpay.com/tenpay.asp");
map.put("service", "pay.weixin.native");
map.put("total_fee", "1000");
map.put("out_trade_no", "ab1406046836");
System.out.println(map.keySet().toString());
第二个场景:按输入顺序排序
JAVA在JDK1.4以后提供了LinkedHashMap来帮助我们实现了有序的HashMap!
Map maps = new LinkedHashMap();
maps.put("1", "张三");
maps.put("2", "李四");
maps.put("3", "王五");
maps.put("4", "赵六");
System.out.println("LinkedHashMap(有序):");
Iterator it = maps.entrySet().iterator();
while(it.hasNext())
{
Map.Entry entity = (Entry) it.next();
System.out.println("[ key = " + entity.getKey() +
", value = " + entity.getValue() + " ]");
}
执行结果如下:
LinkedHashMap(有序):
[ key = 1, value = 张三 ]
[ key = 2, value = 李四 ]
[ key = 3, value = 王五 ]
[ key = 4, value = 赵六 ]
HashMap,LinkedHashMap,TreeMap应用简介
共同点:
HashMap,LinkedHashMap,TreeMap都属于Map;Map 主要用于存储键(key)值(value)对,根据键得到值,因此键不允许键重复,但允许值重复。
不同点:
1.HashMap里面存入的键值对在取出的时候是随机的,也是我们最常用的一个Map.它根据键的HashCode值存储数据,根据键可以直接获取它的值,具有很快的访问速度。在Map 中插入、删除和定位元素,HashMap 是最好的选择。
2.TreeMap取出来的是排序后的键值对。但如果您要按自然顺序或自定义顺序遍历键,那么TreeMap会更好。
3. LinkedHashMap 是HashMap的一个子类,如果需要输出的顺序和输入的相同,那么用LinkedHashMap可以实现.