特点:
无序、以键值对的形式添加元素,键不能重复,值可以重复
它没有继承Collection接口
遍历:
1 先取出保存所有键的Set,再遍历Set即可(2种)
//遍历
//获取所有Keys
Set<String> set=map.keySet();
System.out.println(set);
//获取所有values
Collection<Object> obj=map.values();
for (Object object : obj) {
System.out.println(object);
}
2.先取出保存所有Entry的Set,再遍历此Set即可
//获取所有键值对
Set<Entry<String, Object>> entryset=map.entrySet();
for (Entry<String, Object> entry : entryset) {
System.out.println(entry);
}
entryset.forEach(e->{
System.out.println(e);
});
这里值得一提的是,键是不能重复的,所有我们用跟他特点相同的set集合存储,而value值可以重复,所有我们在这里用list集合的父类collection存储,而键值对由于键是唯一的,所有键值对要用同样特点为唯一的set集合
排序
1.按键排
Map<String, Object> map=new TreeMap<>(Collections.reverseOrder());
map.put("zs", 100);
map.put("ls", 90);
map.put("ww", 80);
System.out.println(map);
2.按值排
Set<Entry<String, Object>> entryset=map.entrySet();
List<Entry<String, Object>> lis=new ArrayList<>(entryset);
Collections.sort(lis,new Comparator<Entry<String, Object>>() {
@Override
public int compare(Entry<String, Object> o1, Entry<String, Object> o2) {
// TODO Auto-generated method stub
return o1.getValue().hashCode()-o2.getValue().hashCode();
}
});
lis.forEach(System.out::println);
在这里调用的其他方法如:1 Collections:工具类,提供一组静态方法操作Collection集合
2 Arrays:工具类,提供了一组静态方法操作数组
collections.reverseOrder()此方法表示倒序输出