目录
一.Map集合的特点
1.无序
2. 以键值对形式存储数据,键唯一,值不唯一
3. 没有继承Collection接口
注意:Map集合键相同时,重复的值被覆盖
二.Map集合的遍历方式
添加对象
Map<String, Integer> map=new HashMap<>();
map.put("zs",100);
map.put("ls",80);
map.put("ww",90);
1、获取所有的keys
Set<String> keys=map.keySet();
for (String key : keys) {
System.out.println(key);
}
2、获取所有的values
Collection<Integer> values=map.values();
for (Integer i : values) {
System.out.println(i);
}
3、获取所有的键值对
Set<Entry<String, Integer>> entrySet = map.entrySet();
遍历
//遍历方法1
for (Entry<String, Integer> entry : entrySet) {
System.out.println("key:"+entry.getKey()+"||value:"+entry.getValue());
}
//遍历方法2
entrySet.forEach(e->{
System.out.println(e.getKey()+"+"+e.getValue());
});
三.排序
1、按照key排序(默认为升序)
降序:在TreeMap中写比较器,调用reverseOrder()方法
Map<String, Object> map=new TreeMap<>(Comparator.reverseOrder());
map.put("zs", 100);
map.put("ls", 80);
map.put("ww", 110);
System.out.println(map);
2.按照vlaue排序
//获取键值对
Set<Entry<String, Object>> entryset = map.entrySet();
//将键值对转换成list集合
List<Entry<String, Object>> lst=new ArrayList<>(entryset);
//使用Collections帮助类进行排序
//collection:集合框架的顶级接口
//Collections:集合框架帮助类
Collections.sort(lst,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();
}
} );
lst.forEach(System.out::println);
四.数组和集合之间的转化
//将数组转换成集合
String a= ("1,2,3,4,5");
String[] split = a.split(",");
List<String> asList = Arrays.asList(split);
System.out.println(asList);
String ss=Arrays.toString(split);
System.out.println(ss);