繁体   English   中英

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

[英]Java8 streams : Filter data from two list of command object. Is there any other efficient way of what i am doing?

我有两个包含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);
});

有没有其他有效的方法呢?

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()
        )
    );

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM