7 java loops class list arraylist
我有一个称为会话的抽象类。讲座和教程扩展了会议。然后,我有一个称为注册的类,其中包含一个会话列表(讲座和教程)。如何在“注册”中的会话列表中循环,并仅从会话列表中返回讲座列表?
我的下一个问题是我应该存储2个列表。一个讲座列表和一个教程列表,而不是一个会话列表?这是因为会话列表对我来说毫无用处,我每次都必须遍历列表以获取有关讲座和教程的信息。有什么办法让我缺少所有讲座的对象吗?我是Java新手。
public class Enrolment {
private List<Session> sessions;
public Enrolment() {
this.sessions = new ArrayList<>();
}
public addSession(Session session) {
this.sessions.add(session);
}
}
Run Code Online (Sandbox Code Playgroud)
public class Session {
private int time;
public Session(int time) {
this.time = time;
}
}
Run Code Online (Sandbox Code Playgroud)
public class Lecture extends Session {
private String lecturer;
public Lecture(int time, String lecturer) {
super(time);
this.lecturer = lecturer;
}
}
Run Code Online (Sandbox Code Playgroud)
public class Tutorial extends Session {
private String tutor;
private int tutorScore;
public Tutorial(int time, String tutor, int tutorScore) {
super(time);
this.tutor = tutor;
this.tutorScore = tutorScore;
}
}
Run Code Online (Sandbox Code Playgroud)
public class test {
public static void main(String[] args) {
Enrolment newEnrolment = new Enrolment();
Lecture morningLec = new Lecture(900, "Dr. Mike");
newEnrolment.addSession(morningLec);
Tutorial afternoonTut = new Tutorial(1400, "John Smith", 3);
newEnrolment.addSession(afternoonTut);
Lecture middayLec = new Lecture(1200, "Mr. Micheals");
newEnrolment.addSession(middayLec);
Tutorial NightTut = new Tutorial(1900, "Harry Pauls", 4);
newEnrolment.addSession(NightTut);
}
}
Run Code Online (Sandbox Code Playgroud)
流式传输sessions
列表并用于instanceof
过滤Lectures
类型对象
List<Lecture> l = sessions.stream()
.filter(Lecture.class::isInstance)
.map(Lecture.class::cast)
.collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)
通过使用for
循环,为每种类型使用两个不同的列表
List<Lecture> l = new ArrayList<>();
List<Tutorial> t = new ArrayList<>();
for (Session s : sessions) {
if (s instanceof Lecture) {
l.add((Lecture) s);
}
else if(s instanceof Tutorial) {
t.add((Tutorial) s);
}
}
Run Code Online (Sandbox Code Playgroud)