how to filter list object by using stream map filter in java

Viewed 46

i want to filter a list of student in java. I have a student class in kotlin like this.

class Student(
    var id: String? = null,
    var firstName: String? = null,
    var lastName: String? = null
) {

    constructor(entity: StudentCourse?): this() {
        if (entity != null) {
            this.id = entity.id.id
            this.name = entity.name
        }
    }
}

class StudentCourse (@EmbeddedId open var id: StudentCourseId)  {
   
    constructor() : this(StudentCourseId())

    open var name: Boolean? = null
}

@Embeddable
open class StudentCourseId: Serializable {

    open var id: String? = null

    open var deptName: String? = null
}

this is the list i want to filter :

var students: List<Student> = listOf(
   Student("14adbv45", "dan", "GEG"),
   Student("96adbv42","Bob", "Bowyer"),
   Student("30adbv45","Emily", "Eden")
 )

I do this

 List<students> studentListContainsFirstNameBob = students.stream()
                        .map(StudentCourse)
                        .filter(e -> e.getFirstName.equals("Bob"))
                        .flatMap(List::stream);

but it doesn't work.

How can i do it please

1 Answers

There are multiple issues in your code. For example in this part:

 constructor(entity: StudentCourse?): this() {
        if (entity != null) {
            this.id = entity.id.id
            this.name = entity.name
        }
    }

The entity.name refers to StudentCourse#name, but this property is actually of Boolean type, so comparing it to String doe snot make much sense. You have also doubled .id which is incorrect.

Next thing, I am not sure what this snipped should do, was the intention to link a student with given course? If so, you would probably like to add a list of students to a course, or a list of courses to a student (which sounds more correct).

Finally, when it comes to filtering a list, you can get students with first name Bob in this way:

var studentListContainsFirstNameBob: List<Student> = students
        .filter { it.firstName.equals("Bob") }
        .toList()

Mind the it variable refers to the element from the list, it could also be written:

var studentListContainsFirstNameBob: List<Student> = students
        .filter { student -> student.firstName.equals("Bob") }
        .toList()
Related