我有两个包含WorkflowCommand
和WorkflowInstanceCommand
的列表。
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 + '\'' +
'}';
}
}
需要打印出两个以上的结果
使用相应的工作流实例查找所有工作流。
查找所有具有正在运行的实例的工作流程以及这些工作流程实例的数量。
首次查询的代码:
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);
});
还有其他有效的方法吗?
答案 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));