gpt4 book ai didi

java - 从链接列表中检索特定数据

转载 作者:行者123 更新时间:2023-11-30 08:12:08 25 4
gpt4 key购买 nike

我想通过流找到性别为女性的学生

学生类(class)

public class Student {
private String first;
private String last;
private int ID;
private Gender gender;

int next=0;

List<Course> courses=new LinkedList<>();
List<Student> students=new LinkedList<>();

public Student(String first, String last, int iD, Gender gender) {
this.first = first;
this.last = last;
ID = iD;
//this.gender = gender;
}

public void enroll(Course c) {
courses.add(c);
}

public void isFemale(){
Student s;
return s.gender=Gender.F;
}
}

枚举性别类

public enum Gender {
M,F;
private Gender gender;
}

public class Main {
public static void main(String[] args) {

List<Student> studentsOfClass=new LinkedList<>();

studentsOfClass.add(new Student("john","smith",01,Gender.M));
studentsOfClass.add(new Student("mick","tayson",05,Gender.M));
studentsOfClass.add(new Student("sara","conor",04,Gender.F));
studentsOfClass.add(new Student("Tana","smith",02,Gender.F));

Course c1=new Course("fiologiya","anna",0234);
Course c2=new Course("mathematics","maria",1134);
Course c3=new Course("phisics","luisa",0534);

studentsOfClass.stream().limit(3).forEach(s->s.enroll(c1));

Collection<Student> femaleStudents= studentsOfClass.stream().filter(Student::isFemale).collect(Collectors.toList());

}
}

最佳答案

您正确使用了 Stream 方法,但是您的 isFamele 方法是错误的。它应该返回 boolean 值并检查当前学生的性别。

应该是:

public boolean isFemale() 
{
return gender==Gender.F;
}

您还应该取消注释此构造函数行 - //this.gender = gender; - 并可能删除 private Gender gender;来自性别枚举。

此外,您可以更改 femaleStudents 的类型来自 CollectionList<Student> , 更准确。

关于java - 从链接列表中检索特定数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30691955/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com