Raj*_*jiv 6 java collections dictionary java-8 java-stream
我List
的Employee
s的不同加入日期。我想在使用流从 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
,因此您可以选择在指定日期之前、之后或加入的人。