从使用 Java 流的员工列表中获取特定加入日期之前和之后的员工

Raj*_*jiv 6 java collections dictionary java-8 java-stream

ListEmployees的不同加入日期。我想在使用流从 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.

  • 这并不完全符合相关代码的作用 - 具有“specifiedDate”的员工将进入“false”分区,而相关代码中的位置则为 none (2认同)

ern*_*t_k 8

如果您的列表可以包含加入 的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,因此您可以选择在指定日期之前、之后或加入的人。

  • -1。您做出了错误的假设,即“compareTo”只会返回 -1、0 或 1。事实上 LocalDate.compareTo 可以返回任何 int。 (2认同)
  • @ernest_k:您可以使用原始的“compareTo”并对其调用“Integer.signum”。 (2认同)