Question: I have some collection List which need to be filtered with below condition in Java 8,
- Arrange the object in the list in a descending order of date (where date can be null as well)
- Iterate each elements of the list one-by-one and validate some condition, if condition matches, then break the iteration their only and return all the elements(till the condition matches) and ignore the remaining elements.
Code snippet:
public class Employee {
private int empId;
private String empName;
private Date empDob;
//Constructor
//Getter Setter
}
Test Class:
public static void main(String[] args) {
List<Employee> asList = Arrays.asList(new Employee(1, "Emp 1", getDate(1998)),
new Employee(2, "Emp 2", getDate(2005)), new Employee(3, "Emp 3", getDate(2000)),
new Employee(4, "Emp 4", null), new Employee(5, "Emp 5", getDate(1990)),
new Employee(6, "Emp 6", new Date()));
List<Employee> result = asList.stream()
.sorted(Comparator.comparing(Employee::getEmpDob, Comparator.nullsLast(Comparator.reverseOrder())))
.filter(i -> i.getEmpName() != null && !StringUtils.isEmpty(i.getEmpName())
&& i.getEmpName().equals("Emp 3"))
.collect(Collectors.toList());
System.out.println(result);
}
public static Date getDate(int year) {
Calendar c1 = Calendar.getInstance();
c1.set(year, 01, 01);
return c1.getTime();
}
The above code which I tried is returning only the element which is matches with the condition and result is:
[Employee [empId=3, empName=Emp 3, empDob=Wed Feb 01 15:55:57 MYT 2000]]
Expected Output which I need to do:
The result which I am expecting is something like below (it should collect all the elements till the condition matches)
[Employee [empId=6, empName=Emp 6, empDob=Sat Aug 15 16:06:22 MYT 2020],
Employee [empId=2, empName=Emp 2, empDob=Tue Feb 01 16:06:22 MYT 2005],
Employee [empId=3, empName=Emp 3, empDob=Tue Feb 01 16:06:22 MYT 2000]]