Java的Collection的遍历方法

迭代器

Java的Collection的遍历方法_第1张图片

package com.itheima.d1;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

public class Test3 {
    public static void main(String[] args) {
        Collection c = new ArrayList<>();
        c.add("赵敏");
        c.add("小昭");
        c.add("素素");
        c.add("灭绝");
        System.out.println(c);
        //从集合对象中获取迭代器对象
        Iterator it = c.iterator();
        while (it.hasNext()){
            String ele = it.next();
            System.out.println(ele);
        }
    }
}

 Java的Collection的遍历方法_第2张图片

增强for循环

Java的Collection的遍历方法_第3张图片

Lambda

 Java的Collection的遍历方法_第4张图片

例子

package com.itheima.d1;

import java.util.ArrayList;
import java.util.Collection;

public class Test4 {
    public static void main(String[] args) {
       Collection movies = new ArrayList<>();
       movies.add(new Movie("《肖生克的救赎》", 9.7, "罗宾斯"));
       movies.add(new Movie("《霸王别姬》", 9.6, "张国荣"));
       movies.add(new Movie("《阿甘正传》", 9.5, "汤姆.汉克斯"));
        for (Movie movie : movies) {
            System.out.println(movie.getName());
            System.out.println(movie.getScore());
            System.out.println(movie.getActor());
        }
    }
}
package com.itheima.d1;

public class Movie {
    private String name;
    private double score;
    private String actor;

    public Movie() {
    }

    public Movie(String name, double score, String actor) {
        this.name = name;
        this.score = score;
        this.actor = actor;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getScore() {
        return score;
    }

    public void setScore(double score) {
        this.score = score;
    }

    public String getActor() {
        return actor;
    }

    public void setActor(String actor) {
        this.actor = actor;
    }

    @Override
    public String toString() {
        return "Movie{" +
                "name='" + name + '\'' +
                ", score=" + score +
                ", actor='" + actor + '\'' +
                '}';
    }
}

你可能感兴趣的:(java,java)