Map的创建
Mapmap1=new HashMap ();
Map的基本 *** 作
//添加对应key值的对象 map1.put("student4",new Student(4,"赵六",90)); //查询key对应的值是否存在 System.out.println(map1.containsKey("student1")); System.out.println(map1.containsValue(map1.get("student2"))) ; //输出map集合 System.out.println(map1); //清空map对象集合 map1.clear(); //判断集合是否为空 map1.isEmpty(); //输出map1对象集合个数 System.out.println(map1.size()); //移除对应的对象 map1.remove("student1") Student student=map1.remove("student1"); System.out.println(student);
Map遍历输出数据的方法
//输出的是一个数组集合 System.out.println(map1.values()); //遍历值集合Collection Collectionvs = map1.values(); for (Student st : vs) { System.out.println(st); } //遍历输出 Set keys = map1.keySet(); for (String k : keys) { //"%s = %s %n"其中%s表示字符串"%s = %s %n"表示数据输出的格式,k代表键名,map1.get(k)代表键值 System.out.printf("%s = %s %n", k, map1.get(k)); } //遍历输出key值和value值 map1.forEach((k, v) -> { System.out.println(k); System.out.println(v); });
Map升序,降序输出数据
Mapmap1= new HashMap (); map1.put("k2","b"); map1.put("k1","ab"); map1.put("k3","cab"); //输出键值的集合 Collection v=map1.values(); System.out.println(v); List list1=new ArrayList (v); //Collections.sort(vs);升序 Collections.sort(list1); System.out.println(list1); //Comparator.reverseOrder()降序 Collections.sort(list1,Comparator.reverseOrder()); System.out.println(list1); //根键名进行排序 Set keys = map1.keySet(); List list2=new ArrayList (keys); //升序排列 Collections.sort(list2); System.out.println(list2); //降序排列 Collections.sort(list2,Comparator.reverseOrder()); System.out.println(list2); //根据values的长度进行排序:升序 list1.sort(Comparator.comparingInt(String :: length)); System.out.println(list1); //降序 list1.sort((a,b)->b.length()-a.length()); System.out.println(list1);
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)