gpt4 book ai didi

Java8 流 : Filter data from two list of command object. 我在做什么还有其他有效的方法吗?

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:07:35 25 4
gpt4 key购买 nike

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

如果您想排除具有 0 个实例的 WorkflowCommand,您必须将此行添加到第二个查询:

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

关于Java8 流 : Filter data from two list of command object. 我在做什么还有其他有效的方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52387278/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com