从LinkedList中检索特定数据

时间:2015-06-07 09:25:48

标签: java

我希望通过使用溪流找到性别为女性的学生

Student上课

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;
    }
}
性别

enum课程

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

main上课

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());

    }
}

1 个答案:

答案 0 :(得分:3)

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

应该是:

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

您还应该取消标记此构造函数行 - //this.gender = gender; - 并且可能会从Gender枚举中删除private Gender gender;

此外,您可以将femaleStudents的类型从Collection更改为List<Student>,这样更准确。