0

I am using java 8
I have a model class like

class Student{
    String name;
    List<Subject> subjects1;
    List<Subject> subjects2;
    List<Subject> subjects3;
    // getters & setters
}

class Subject{
    String sub;
    Integer marks;
    boolean status;
    // getters & setters
}

status may be true or false.
Now if the status is false then I have to remove those objects from the subjects list
How to do it in Streams?
Thanks in advance.

4
  • 1
    Does this answer your question? Java - removeIf example Commented Nov 3, 2021 at 10:15
  • Is it a list of students or just a list of subjects that you are dealing with here? Commented Nov 3, 2021 at 10:20
  • @Turamarth It doesn't answer this question. Commented Nov 3, 2021 at 10:27
  • @mang4521 It is not a list of Student. There is one student having list of subject and marks. Commented Nov 3, 2021 at 10:28

4 Answers 4

5

To remove objects, you can directly use removeIf method in java 8.

student.getSubjects().removeIf(subject -> !subject.isStatus());

Sign up to request clarification or add additional context in comments.

2 Comments

This works fine. Considering there are many lists in Student, Just for examle I have given subjects1, subjects2 etc. In this case can we do it dynamically? In the sence without knowing how many lists of Subject.
You can use java reflection in that case.
3

Here's how you do it:

List<Student> studentsWithTrueStatus = students
  .stream()
  .filter( s -> s.status )
  .collect(Collectors.toList());

3 Comments

This is an alternative solution to removing items from the students. It does not really remove anything.
You can just replace the original list with this one. This solves the problem.
Sure, and it's not wrong to do so, I just wanted to point out that this code produces a new list instead of removing items from the source list. Might be of interest for specific readers.
1

If there are multiple lists of Subject in Student class, they may be joined using Stream.of and then applying removeIf in forEach:

// Some utility class MyClass
public static void removeSubjects(Student student) {
    Stream.of(student.getSubjects1(), student.getSubjects2(), student.getSubjects3())
        .filter(Objects::nonNull) // filter out null lists if any
        .forEach(subjects -> subjects.removeIf(sub -> !sub.isStatus()));
}

If there is a list of students, then the reference to the above implemented method may be used for each student:

List<Students> students = Arrays.asList(...); // setup students list

students.forEach(MyClass::removeSubjects);

Comments

0

First ensure the list of subjects is not null or empty. Then utilise removeIf() method.

List<Subject> subjectList = student.getSubjects();

if((null != subjectList) && (subjectList.size() > 0)) {
  subjectList.removeIf(sub -> !(sub.isStatus()));
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.