栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Map集合的基本用法

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Map集合的基本用法

Map的创建

Map map1=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
        Collection vs = 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升序,降序输出数据

 Map map1= 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);
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/697668.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号