Java8流:从两个命令对象列表中过滤数据。我还有其他有效的方式吗?

时间:2018-09-18 13:04:59

标签: java collections java-8 java-stream

我有两个包含WorkflowCommandWorkflowInstanceCommand的列表。

public List<WorkflowCommand> workflowList = new ArrayList<>();
public List<WorkflowInstanceCommand> workflowInstanceList = new ArrayList<>();

public class WorkflowCommand {

  int id;
  String name;
  String author;
  int version;

  @Override
  public String toString() {
    return "WorkflowCommand{" +
            "id=" + id +
            ", name='" + name + '\'' +
            ", author='" + author + '\'' +
            ", version=" + version +
            '}';
  }

}



public class WorkflowInstanceCommand {

  long id;
  int workflowId;
  String assignee;
  String step;
  String status;

  @Override
  public String toString() {
    return "WorkflowInstanceCommand{" +
            "id=" + id +
            ", workflowId=" + workflowId +
            ", assignee='" + assignee + '\'' +
            ", step='" + step + '\'' +
            ", status='" + status + '\'' +
            '}';
  }
}

需要打印出两个以上的结果

  1. 使用相应的工作流实例查找所有工作流。

  2. 查找所有具有正在运行的实例的工作流程以及这些工作流程实例的数量。

首次查询的代码:

workflowList.forEach(w -> {
    System.out.println("==workflow data=="+w);
    workflowInstanceList.stream()
            .filter(wi -> w.getId() == wi.getWorkflowId())
            .forEach(System.out::println);
});

第二个查询的代码:

workflowList.forEach(w -> {
    List<WorkflowInstanceCommand> instanceCommands = workflowInstanceList.stream()
        .filter(wi -> w.getId() == wi.getWorkflowId())
        .filter(wi -> wi.getStatus().equals("RUNNING"))
        .collect(Collectors.toList());

    System.out.println("==workflow data=="+w+"===size=="+instanceCommands.size());
    instanceCommands.forEach(System.out::println);
});

还有其他有效的方法吗?

1 个答案:

答案 0 :(得分:2)

import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.toMap;

第一个查询:

Map<WorkflowCommand, List<WorkflowInstanceCommand>> instancesByWorkflow =
    workflowInstanceList.stream()
        .collect(groupingBy(WorkflowInstanceCommand::getWorkflowId))
        .entrySet().stream()
        .collect(toMap(e -> workflowList.get(e.getKey()), Map.Entry::getValue));

第二个查询:

Map<WorkflowCommand, Integer> numberOfRunningInstancesByWorkflow =
    .collect(
        toMap(
            e -> e.getKey(),
            e -> e.getValue().stream().filter(i -> i.getStatus().equals("RUNNING")).count()
        )
    );

,如果要使用0个实例排除WorkflowCommand,则必须将此行添加到第二个查询中:

.entrySet().stream()
    .filter(e -> e.getValue() != 0)
    .collect(toMap(Map.Entry::getKey, Map.Entry::getValue));