I have a map of employee name and employee salary and I want to return a list of employees' names whose salary is less than or equal to the salary passed as an argument using lambda and functional interface. This is what I am doing but it is showing me an error this method should return a result of the type list.
public static EmployeeAudit findEmployee() {
return salary ->
employeeMap.entrySet()
.stream()
.filter(s -> s.getValue() <= salary)
.collect(Collectors.toList());
}
public interface EmployeeAudit {
ArrayList<String> fetchEmployeeDetails (double salary);
}
It's better to use an abstraction (interface) over a particular implementation. This satisfies most of the contracts. Note that Collectors.toList()
results in List<T>
and not ArrayList<T>
- the return types are incompatible. Start with:
public interface EmployeeAudit {
List<String> fetchEmployeeDetails (double salary);
}
Now returning EmployeeAudit
as a lambda expression. I assume employeeMap
is Map<String, Double>
hence you need to map (transform) Stream into the Map
's key using Stream#map(Function)
:
public static EmployeeAudit findEmployee() {
return salary -> employeeMap.entrySet()
.stream()
.filter(s -> s.getValue() <= salary)
.map(Map.Entry::getKey)
.collect(Collectors.toList());
}
}