I'm trying to find all the employees whose salary is greater than 50k using a lambda expression.
But I'm not able to access the getSalary()
method.
ArrayList<emp> list=new ArrayList<>();
list.add(new emp("Ronaldo",1,90000,"UTD"));
list.add(new emp("Rooney",2,40000,"HOME"));
Predicate<ArrayList<emp>> p3 = (s) -> s.getSalary() > 50000;
System.out.println(p3.test(list));
CodePudding user response:
Try this!
List<Employees> empGreaterThan = list.stream().filter(emp -> emp.getSalary() > 5000).collect(Collectors.toList());
Make sure getSalary()
is defined in your Employee class or you are using Lombok
or similar plugin to generate Getter/setters !
Alternatively, if you want to define your own predicate, you can do like this
Predicate<Employee> myPredicate= emp -> emp.getSalary() > 5000;
List<Employee> newList= list.stream().filter(myPredicate).collect(Collectors.toList());
CodePudding user response:
Predicate
is a functional interface built-in the JDK representing a boolean
-value function.
It's method test()
returns true
or false
it's meant to verify whether an object passed as an argument matches the condition.
Sidenote: get familiar with Java Naming conventions, emp
- ins't a good name for a class. And also have a look at this question What does it mean to "program to an interface"?
Your definition and usage of the predicate is incorrect:
(s) -> s.getSalary() > 50000
Argument s
is of type List<Employee>
, therefore you can't apply getSalary()
on it.
And your expectation that p3.test(list)
will give a list as a result is also wrong. Predicate is meant to produce a boolean
value and nothing more.
Instead, you need to iterate over the list of employee and apply the predicate on each element in the list during the iteration process.
The most convenient way approach is to create a stream (as shown in the answer by @Harsh). You can also do it using a plain for
loop.
public static Predicate<Employee> salaryGraterThen(int salary) {
return emp -> emp.getSalary() > salary;
}
Predicate<Employee> salaryGraterThen50K = salaryGraterThen(50_000);
List<Employee> result = new ArrayList<>();
for (Employee emp: list) {
if (salaryGraterThen50K.test(emp)) result.add(emp);
}
It can also be done using removeIf()
method of the Collection
interface, that expects a Predicate
as an argument and will remove every element for which the given predicate will be evaluated to true
.
For that, we need to make a copy of the initial list (to keep it intact):
List<Employee> result = new ArrayList<>(list);
result.removeIf(emp -> emp.getSalary() <= 50_000);