HashMap的几种遍历方法

public class HashMapDemo {
    public static void main(String[] args) {
        HashMap<String, Student> hashMap = new HashMap<>();
        hashMap.put("001",new Student(1,"张三",12));
        hashMap.put("002",new Student(2,"张三1",14));
        hashMap.put("003",new Student(3,"张三2",11));
        hashMap.put("004",new Student(4,"张三3",17));

        //遍历KeySet,获取HashMap中的key
        Set<String> strings = hashMap.keySet();
        for (String k : strings){
            System.out.println(k+":"+hashMap.get(k).getName());
        }

        //使用返回Collection集合
        Collection<Student> values = hashMap.values();
        for (Student s : values){
            System.out.println(s);
        }

        //使用entrySet()
        Set<Map.Entry<String, Student>> entries = hashMap.entrySet();
        for (Map.Entry<String, Student> e :  entries){
            System.out.println(e.getKey());
            System.out.println(e.getValue());
        }

        //使用迭代器,使用迭代器接口Iterator 接口
        Iterator<Student> iterator = hashMap.values().iterator();
        while (iterator.hasNext()){
            System.out.println(iterator.next());
        }
        //获取键值,取得内容
        Iterator<String> iterator1 = hashMap.keySet().iterator();
        while (iterator1.hasNext()){
            String key = iterator1.next();
            System.out.println(hashMap.get(key));
        }
    }
}

HashMap是非线程安全,Hashtable是线程安全的,如果在单线程main线程程序中,使用了

线程安全的工具类,效率就低,根据使用量上来说还是HashMap使用的多。

集合接口及工具类总结:

Collection 接口

List 接口

ArrayList 动态数组,有序 插入删除速度慢,读取速度

LinkedList 双向链表,插入删除速度快,读取速度慢

Vector 动态数组,线程安全

Set 接口

HashSet 唯一集合,无序

TreeSet 唯一集合,是有序

Map 接口

HashMap K,V键值对集合,双列集合

TreeMap 根据key有序的map集合

Hashtable 和 HashMap一样,双列集合,线程安全

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值