我有 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;
}
有没有办法在单流中做到这一点?
最佳答案
您可以使用 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返回一个根据谓词对输入元素进行分区的收集器,并将它们组织成一个
Map<Boolean, List<T>>
请注意,这不会处理具有
specificDate
的员工.
关于java - 从使用 Java 流的员工列表中获取特定加入日期之前和之后的员工,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59573393/