Home > database >  How to use removeIf() to remove 2 conditions?
How to use removeIf() to remove 2 conditions?

Time:10-09

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

Ex. Want to remove whoes grade is below ‘B’

Code as following:

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

CodePudding user response:

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';

CodePudding user response:

Predicate<Student> condition = p->p.grade=='C'&& p.grade=='B';
students.removeIf(condition);

Should be

Predicate<Student> condition = p->p.grade=='C'|| p.grade=='B';
students.removeIf(condition);

It's impossible for a student's grade to be both B and C, so the predicate you provided will never be true.

Also, it's possible to chain together two predicates with the and() and or() methods like so:

Predicate<Student> condition = p->p.grade=='C'
Predicate<Student> condition2 = p->p.grade=='B';
students.removeIf(condition.or(condition2);
// students.removeIf(condition.and(condition2); works similarly but with logical and

https://howtodoinjava.com/java8/predicates-logical-operations/

CodePudding user response:

You also could try to do something like:

Predicate<Student> condition = p-> ((int) p.grade) > 65;

'A' char in ASCII is 65, so any letter after A, like B - 66, C - 67, D - 68 are higher.

However it is not particularly safe to do this. Because what if You pass a '@' as grade char..

I would most probably introduce a Enum with grades. And in enum instroduce a method isLessThenA() In method I would check if value is of ssome enum type and if not, would throw an Exception.

CodePudding user response:

The other answers are correct. As an alternative, why not just two calls to removeIf()?

students.removeIf(p->p.grade=='C');
students.removeIf(p->p.grade=='B');

I find it clear to read, and neither you nor your reader needs to consider whether it should have been && or ||.

  • Related