java中 list ,set,map常用的遍历方法

import java.util.*;

public class Collections {
    public static void main(String[] args) {
        List<String> list=new ArrayList<>();
        list.add("1111");
        list.add("2222");
        list.add("3333");
        list.add("4444");

        System.out.println("list输出");
        //普通循环方式遍历输出
        for (int i = 0; i < list.size(); i++) {
            System.out.println(list.get(i));
        }
        System.out.println("----------------------");
        //使用迭代器进行输出
        Iterator<String> iterator = list.iterator();
        while (iterator.hasNext()){
            System.out.println(iterator.next());
        }
        System.out.println("----------------------");
        //增强for循环
        for (String s: list){
            System.out.println(s);
        }
        System.out.println("++++++++++++");
        //函数式编程 输出 简洁
        list.forEach(System.out::println);

        System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~");
        Set<String> set=new HashSet<>();

        set.add("aaa");
        set.add("bbb");
        set.add("ccc");
        set.add("ddd");
        System.out.println("set输出");
        //增强for循环输出
        for (String s :set){
            System.out.println(s);
        }

        //迭代器输出
        System.out.println("----------------------");
        Iterator<String> iterator1 = set.iterator();
            while (iterator1.hasNext()){
                System.out.println(iterator1.next());
            }

         Map<String,String> map=new HashMap<>();
            map.put("111","aaa");
            map.put("222","bbb");
            map.put("333","ccc");
            map.put("444","ddd");
        System.out.println("__________________________");
        System.out.println("map输出");
        Set<Map.Entry<String, String>> entries = map.entrySet();
        //利用entrySet获得键值对
        for (Map.Entry<String, String> s:entries){
            String key = s.getKey();
            String value = s.getValue();
            System.out.println(key+":"+value);
        }
        System.out.println("______________________");
        //单独获得键值
        Set<String> keySet = map.keySet();
        for (String s:keySet){
            System.out.println(s);
        }
        //单独获得value
        System.out.println("_______________________");
        Collection<String> values = map.values();
        for (String s:values){
            System.out.println(s);
        }

    }

}

posted @ 2021-04-20 09:19  Cherish°  阅读(103)  评论(0编辑  收藏  举报