[英]Get Employees before and after specific date of joining from List of Employees with Java stream
我有不同加入日期的Employee
List
。 我想在使用流從 List 加入的特定日期之前和之后獲取員工。
我試過下面的代碼,
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;
}
有沒有辦法在單流中做到這一點?
您可以使用partitioningBy
如下,
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返回一個收集器,它根據 Predicate 對輸入元素進行分區,並將它們組織成Map<Boolean, List<T>>
請注意,這不會處理具有specificDate
員工。
如果您的列表可以包含在specificDate
上加入的條目,那么您可能會發現groupingBy
很有用:
Map<Integer, List<Employee>> result = employeeList.stream()
.map(emp -> new AbstractMap.SimpleEntry<>(specificDate.compareTo(emp.getJoiningDate()), emp))
.collect(Collectors.groupingBy(entry -> entry.getKey() > 0 ? 1 : (entry.getKey() < 0 ? -1 : 0),
Collectors.mapping(entry -> entry.getValue(), Collectors.toList())));
employeeListAfter = result.get(-1);
employeeListBefore = result.get(1);
employeeListOnSpecificDate = result.get(0);
result
映射包含相對於specificDate
按職位分組的Employee
記錄,因此您可以選擇在指定日期之前、之后或加入的人員。
您需要過濾掉具有此特定日期的員工。 然后你可以使用分區:
Map<Boolean, List<Employee>> partitioned = employeeList.stream()
.filter(e -> !e.joiningDate.equals(specificDate))
.collect(partitioningBy(e -> e.joiningDate.isAfter(specificDate)));
List<Employee> employeeListAfter = partitioned.get(true);
List<Employee> employeeListBefore = partitioned.get(false);
這將根據集合是否滿足謂詞來創建集合映射。
您可以使用Collectors.groupingBy
並使用compareTo
方法根據之前、當前和未來日期對員工列表進行分組
Map<Integer, List<Employee>> result = employeeList.stream()
.collect(Collectors.groupingBy(e-> e.joiningDate.compareTo(specificDate)< 0 ? -1 : (e.joiningDate.compareTo(specificDate) == 0 ? 0 : 1)));
所以輸出將是
key--> -1 ---> will have employees with previous date
key--> 0 ---> will have employees with current date
key--> 1 ---> will have employees with future date
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.