How would you write a Java Stream to fetch all employees under the age of thirty?
Question Explain
The question is asking you to demonstrate your ability to use Java Streams, specifically to filter out a collection of objects based on a certain property of those objects. In this case, you need to filter a collection of Employee objects to include only those whose age is less than 30. To answer this question effectively, these are the key points you should keep in mind:
- You need to know how to use the
filter()function of Java Streams. - You need to be able to write a lambda expression to apply to each object in the stream. This can be simple, in this case you want to compare the
ageproperty of eachEmployeeobject to the number 30. - A crucial thing is how you terminate the stream operation. You have to decide whether to collect the result into a new list or process it in some other way.
Answer Example 1
Suppose we have a List of Employee objects named allEmployees. The Java Stream to fetch all employees under the age of 30 would look something like this:
List<Employee> youngEmployees = allEmployees.stream()
.filter(e -> e.getAge() < 30)
.collect(Collectors.toList());
In this example, we use the stream() function to convert the list to a stream, then filter() to filter the stream based on the age of each Employee, and finally collect() to convert the stream back into a list.
Answer Example 2
Another way of approaching this d could be using Java Stream to loop through employees and print details of younger employees. Here's an example:
allEmployees.stream()
.filter(e -> e.getAge() < 30)
.forEach(e -> System.out.println(e.getName() + " " + e.getAge()));
In this case, instead of collecting the result into a new list, we directly print the name and age of each qualified employee.