javaremove-if

How to use removeIf() to remove 2 conditions?


I want to use removeIf to remove 2 conditions, but I did not find the proper way to do that.

For example, I want to remove students whose grade is below ‘B’

Code as follows:

Student[] group1 = {new Student(), new Student(), new Student(), new Student()};

group1[0].setInfo("Davut", 'M', 123, 'A');
group1[1].setInfo("Ali", 'M', 43, 'B');
group1[2].setInfo("Ivan", 'M', 34, 'B');
group1[3].setInfo("Lily", 'F', 67, 'C');

System.out.println(Arrays.toString(group1));

ArrayList<Student> students = new ArrayList<>();
students.addAll(Arrays.asList(group1));
System.out.println("--------------");
Predicate<Student> condition = p->p.grade=='C'&& p.grade=='B';
students.removeIf(condition);

Solution

  • The issue is with this line:

    Predicate<Student> condition = p->p.grade=='C'&& p.grade=='B';
    

    You'r asking to remove a student that has grade 'C' AND 'B'. It should be 'C' OR 'B'.

    Replace with this:

    Predicate<Student> condition = p->p.grade=='C' || p.grade=='B';