I have List
of Employee
s with different joining dates. I want to Get Employees before and after specific date of joining from List using streams.
i tried following code,
List<Employee> employeeListAfter = employeeList.stream()
.filter(e -> e.joiningDate.isAfter(specificDate))
.collect(Collectors.toList());
List<Employee> employeeListBefore = employeeList.stream()
.filter(e -> e.joiningDate.isBefore(specificDate))
.collect(Collectors.toList());
class Employee{
int id;
String name;
LocalDate joiningDate;
}
Is there any way to do this in single stream?
The joining() method of the Collectors class in Java 8 returns a Collector that concatenates the input elements into a String, in encounter order. Here, CharSequence is a readable sequence of char values, whereas String class represents character strings.
Stream of(T t) returns a sequential Stream containing a single element. Syntax : static Stream of(T t) Parameters: This method accepts a mandatory parameter t which is the single element in the Stream. Return Value: Stream of(T t) returns a sequential Stream containing the single specified element.
Using List. stream() method: Java List interface provides stream() method which returns a sequential Stream with this collection as its source.
A stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result. The features of Java stream are – A stream is not a data structure instead it takes input from the Collections, Arrays or I/O channels.
You can use partitioningBy
as below,
Map<Boolean, List<Employee>> listMap = employeeList.stream()
.collect(Collectors.partitioningBy(e -> e.joiningDate.isAfter(specificDate)));
List<Employee> employeeListAfter = listMap.get(true);
List<Employee> employeeListBefore = listMap.get(false);
partitioningBy Returns a Collector which partitions the input elements according to a Predicate, and organizes them into a Map<Boolean, List<T>>
Note that this won't handle employees with specificDate
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With