关于java集合框架(四):常用集合类的遍历方法

时间:2021-09-29 17:04:10

ArrayList遍历:

public class Test{
    public static void main(String[] args) {
        List<String> list = new ArrayList<String>();
        list.add("abc");
        list.add("def");
        list.add("ghi");
        //使用foreach遍历
        for(String s : list){
            System.out.println(s);
        }
        //变为普通数组遍历
        String[] array = new String[list.size()];
        list.toArray(array);
        for(String s : array){
            System.out.println(s);
        }
        //使用迭代器(iterator)进行遍历
        Iterator<String> iterator= list.iterator();
        while(iterator.hasNext()){
            System.out.println(iterator.next());
        }
    }
}

LinkedList遍历:与ArrayList基本一致

Map遍历:

public class Test{
    public static void main(String[] args) {
        Map<String,String> map = new HashMap<String, String>();
        map.put("1","value1");
        map.put("2","value2");
        map.put("3","value3");

        //通过keySet遍历
        for(String key : map.keySet()){
            System.out.println(key + ":" + map.get(key));
        }
        //通过iterator遍历
        Iterator<Map.Entry<String,String>> iterator = map.entrySet().iterator();
        while(iterator.hasNext()){
            Map.Entry<String,String> entry = iterator.next();
            System.out.println(entry.getKey() + ":" + entry.getValue());
        }
        //通过Map,entrySet使用foreach遍历
        for(Map.Entry<String,String> entry : map.entrySet()){
            System.out.println(entry.getKey() + ":" + entry.getValue());
        }
        //通过map.Values()遍历所有的value,但不能遍历key
        for(String v : map.values()){
            System.out.println(v);
        }
    }
}

Set遍历:

public class Test{
    public static void main(String[] args) {
        Set<String> set = new HashSet<String>();
        set.add("s1");
        set.add("s2");
        set.add("s3");
        //普通的foreach遍历
        for(String s : set){
            System.out.println(s);
        }
        Iterator<String> iterator = set.iterator();
        while(iterator.hasNext()){
            String s = iterator.next();
            System.out.println(s);
        }
    }
}