I have a list of Employee
, and I want to retrieve only one Employee
information with the specific name:
public static Employee getAllEmployeeDetails(String employeeName) {
List<Employee> empList = getAllEmployeeDetails();
Employee employee = empList.stream().filter(x -> x.equals(employeeName));
return employee;
}
Please let me know how to filter the data and return a single element.
-
I’d suggest renaming your method to "getEmployeeByName" as opposed to "getAllEmployeeDetails". readability is very important.Ousmane D.– Ousmane D.2018年12月11日 09:23:13 +00:00Commented Dec 11, 2018 at 9:23
3 Answers 3
This will locate the first Employee
matching the given name, or null
if not found:
Employee employee = empList.stream()
.filter(x -> x.getName().equals(employeeName))
.findFirst()
.orElse(null);
You're looking for findFirst
or findAny
:
empList.stream()
.filter(x -> x.getName().equals(employeeName))
.findFirst()
or
empList.stream()
.filter(x -> x.getName().equals(employeeName))
.findAny();
However, I'd suggest changing the method return type with the use of Optional
which is intended for use as a method return type where
there is a need to represent "no result" . in other words we let the "client" decide what to do in the "no value" case. i.e.
public static Optional<Employee> getAllEmployeeDetails(String employeeName) {
return empList.stream()
.filter(x -> x.getName().equals(employeeName))
.findFirst()
}
you could have done .findFirst().orElse(null)
but dealing with nullity
is sometimes dangerous and this is a perfect opportunity to leverage the Optional<T>
API.
-
1Yup, this is indeed good advice: drop nulls, return Optionals.MC Emperor– MC Emperor2018年12月11日 07:23:12 +00:00Commented Dec 11, 2018 at 7:23
-
or maybe
orElseThrow
if the get is critical based on theemployeeName
, thoughts?Naman– Naman2018年12月11日 08:33:27 +00:00Commented Dec 11, 2018 at 8:33 -
@nullpointer good shout! I’ll have to say it depends and is debatable but personally I’d proceed with the suggested approach because it provides more options to the client and the method signature with an Optional return type is very meaningful/readable.Ousmane D.– Ousmane D.2018年12月11日 09:17:32 +00:00Commented Dec 11, 2018 at 9:17
Hi You can use multiple ways to get single object from list here i just modified the method names and also some variable names so that the code should be readable and also try to use Optional as it handles null pointer
public static Employee findEmployeeByName(String employeeName) {
List<Employee> empList = getAllEmployeeDetails();
Optional<Employee> employee = empList.stream()
.filter(employee -> employee.getName().equalsIgnoreCase(employeeName))
.findFirst();
return employee.isPresent() ? employee.get() : null; // Instead of null you can also return empty Employee Object
}