Map集合的基本用法

Map的创建

Map<String,Student> map1=new HashMap<String,Student>();

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<Student> vs = map1.values();
        for (Student st : vs) {
            System.out.println(st);
        }
//遍历输出
    Set<String> 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<String, String> map1= new HashMap<String, String>();
  map1.put("k2","b");
  map1.put("k1","ab");
  map1.put("k3","cab");
  //输出键值的集合
  Collection<String> v=map1.values();
  System.out.println(v);
  List<String> list1=new ArrayList<String>(v);
  //Collections.sort(vs);升序
  Collections.sort(list1);
  System.out.println(list1);
  //Comparator.reverseOrder()降序
  Collections.sort(list1,Comparator.reverseOrder());
  System.out.println(list1);
  //根键名进行排序
  Set<String> keys = map1.keySet();
  List<String> list2=new ArrayList<String>(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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值