需求:
某影院系统需要在后台存储三部电影,然后依次展示出来。
《肖生克的救赎》,9.7,罗宾斯
《霸王别姬》,9.6,张国荣、张丰毅
《阿甘正传》,9.5,汤姆.汉克斯
电影类
package com.xzhao.Collection;
public class Moive {
private String name;
private double score;
private String actor;
public Moive(String name, double score, String actor) {
this.name = name;
this.score = score;
this.actor = actor;
}
public String getName() {
return name;
}
public double getScore() {
return score;
}
public String getActor() {
return actor;
}
public void setName(String name) {
this.name = name;
}
public void setScore(double score) {
this.score = score;
}
public void setActor(String actor) {
this.actor = actor;
}
}
实现
package com.xzhao.Collection;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.function.Consumer;
public class test {
public static void main(String[] args) {
Collection<Moive> mo = new ArrayList<>();
Moive s1 = new Moive("肖生克的救赎", 9.7, "罗宾斯");
mo.add(s1);//通过变量新增
mo.add(new Moive("霸王别姬", 9.6, "张国荣、张丰毅"));//也可以直接这样写
mo.add(new Moive("阿甘正传", 9.5, "汤姆.汉克斯"));
System.out.println("------------------使用for增强遍历输出----------------------");
for (Moive moive : mo) {
System.out.println("电影名:" + moive.getName() + ",分值:" + moive.getScore() + ",主演:" + moive.getActor());
}
System.out.println("----------------使用迭代器遍历输出------------------------");
Iterator<Moive> it = mo.iterator();
while (it.hasNext()){
Moive ele = it.next();
System.out.println("电影名:" + ele.getName() + ",分值:" + ele.getScore() + ",主演:" + ele.getActor());
}
System.out.println("----------------使用(jdk8)ForEace表达式------------------------");
mo.forEach(new Consumer<Moive>() {
@Override
public void accept(Moive moive) {
System.out.println("电影名:" + moive.getName() + ",分值:" + moive.getScore() + ",主演:" + moive.getActor());
}
});
System.out.println("----------------使用lambda表达式(简化)------------------------");
mo.forEach((Moive moive) -> {
System.out.println("电影名:" + moive.getName() + ",分值:" + moive.getScore() + ",主演:" + moive.getActor());
});
}
}
运行截图