Raj*_*jiv 6 java collections dictionary java-8 java-stream
我List的Employees的不同加入日期。我想在使用流从 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;
}
Run Code Online (Sandbox Code Playgroud)
有没有办法在单流中做到这一点?
Cod*_*ode 13
您可以使用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);
Run Code Online (Sandbox Code Playgroud)
partitioningBy返回一个收集器,它根据谓词对输入元素进行分区,并将它们组织成一个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);
Run Code Online (Sandbox Code Playgroud)
该result地图包含Employee按相对于 的位置分组的记录specificDate,因此您可以选择在指定日期之前、之后或加入的人。
| 归档时间: |
|
| 查看次数: |
1245 次 |
| 最近记录: |