Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Employees before and after specific date of joining from List of Employees with Java stream

I have List of Employees 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?

like image 825
Rajiv Avatar asked Jan 03 '20 04:01

Rajiv


People also ask

What does collectors joining () do?

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.

What does stream of () method in Java?

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.

How can we get a stream from a List in Java?

Using List. stream() method: Java List interface provides stream() method which returns a sequential Stream with this collection as its source.

What is tream in Java?

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.


1 Answers

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.

like image 91
Vikas Yadav Avatar answered Oct 27 '22 01:10

Vikas Yadav