集合框架Map的基本方法和常用遍历方式

package demo.assemble;

import org.junit.Test;

import java.util.*;

//key值 是无序,不重复的
public class 集合框架_Map基本方法和遍历 {
    //基本方法演示
    @Test
    public void demo() {
        Map<Integer, String> m = new HashMap<>();
        m.put(1, "a");
        m.put(2, "b");
        System.out.println(m.put(3, "c"));//null   返回与键相关联的旧值
        System.out.println(m.put(3, "d"));//c
        System.out.println("打印:" + m);//{1=a, 2=b, 3=d}
        System.out.println("长度:" + m.size());//3
        System.out.println("是否为空:" + m.isEmpty());//false
        System.out.println("删除:" + m.remove(3));//d 返回其值
        System.out.println("删除后:" + m);//{1=a, 2=b}
        System.out.println("是否包含指定键:" + m.containsKey(1));//true
        System.out.println("是否包含指定值:" + m.containsKey(2));//true
        System.out.println("获取指定键的值:" + m.get(1));//a   没有返回null
    }

    //遍历map 利用ketSet方法
    @Test
    public void traverseMap() {
        Map<Integer, String> m = new HashMap<>();
        m.put(3, "c");
        m.put(2, "b");
        m.put(1, "a");
        Set<Integer> s = m.keySet();//将map中键key集合全部给Set集合的对象keySet

        Iterator<Integer> it = s.iterator();//构建一个set集合的迭代器
        while (it.hasNext()) {//使用set迭代器迭代key
            Integer key = it.next();
            String value = m.get(key);
            System.out.println(key + ":" + value);
        }
    }

    //遍历map 利用entrySet()方法
    @Test
    public void traverseMap2() {
        Map<Integer, String> m = new HashMap<>();
        m.put(3, "c");
        m.put(2, "b");
        m.put(1, "a");

        Set<Map.Entry<Integer, String>> s = m.entrySet();//将键值关系存入Set集合 键唯一
        Iterator<Map.Entry<Integer, String>> it = s.iterator();//构建一个set集合的迭代器
//        Iterator<Map.Entry<Integer,String>> it = m.entrySet().iterator();

        while (it.hasNext()) {
            Map.Entry<Integer, String> me = it.next();
            //me.getKey();
            //me.getValue();
            System.out.println(me);
        }
    }

    //遍历map中的value值
    @Test
    public void traverseMapValue() {
        Map<Integer, String> m = new HashMap<>();
        m.put(3, "c");
        m.put(2, "b");
        m.put(1, "a");

        Collection<String> coll = m.values();//将值关系存入集合    值不唯一 无需Set集合
        Iterator<String> it = coll.iterator();
        while (it.hasNext()) {
            System.out.println(it.next());
        }
    }
}
/**
 * Map常用的子类:
 * |--Hashtable :内部结构是哈希表,是同步的。不允许null作为键,null作为值。
 * |--Properties:用来存储键值对型的配置文件的信息,可以和IO技术相结合。
 * |--HashMap : 内部结构是哈希表,不是同步的。允许null作为键,null作为值。
 * |--TreeMap : 内部结构是二叉树,不是同步的。可以对Map集合中的键进行排序。
 */
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值