java 集合(Map2)

Map 接口的迭代方法:

import java.util.*;

public class ex12 {
    public static void main(String[] args) {
        Map<String, String> map = new HashMap<String, String>();//为什么改成int会报错
        map.put("Tom", "1");
        map.put("Jack", "2");
        map.put("Yoo", "3");
        map.put("Peter", "4");
        map.put("LiLi", "5");
        System.out.println(map);

        //双列集合没有迭代器就只好借用单列集合的,所以不能同时返回

      //map 集合中遍历   方式一   使用KeySet(Map接口中的方法) 方法进行遍历  缺点:只有键没有值,还的自己找值
        Set<String> keys = map.keySet();
        Iterator<String> it = keys.iterator();
        while (it.hasNext()){
            String key = it.next();//注意
            System.out.println("键:"+ key + "   " + "值:" + map.get(key));
        }

        //map 集合中遍历   方式二: 使用values  Collection<V> values()   缺点:只有值没有键
        Collection<String> c = map.values();
        Iterator<String> it2 = c.iterator();
        while (it2.hasNext()){
            System.out.println("值:" + it2.next());
        }
        //那么如何能返回一个单列集合然后存键和值的数据呢?同时不能破坏数和值之间的关系
        //答:自定义类
        //map 集合中遍历   方式三   entrySet方法遍历
        Set<Map.Entry<String,String >> entrys = map.entrySet();
        Iterator<Map.Entry<String,String>> it3 = entrys.iterator();
        while(it.hasNext()){
            Map.Entry<String,String> entry = it.next();//有错但不知道错哪了
            System.out.println(entry.getKey() + entry.getValue());

        }
    }
}
原文地址:https://www.cnblogs.com/lifehrx/p/5802507.html