【发布时间】:2020-05-25 14:55:29
【问题描述】:
我有一个客户对象列表如下:
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class CheckForResource {
public static void main(String[] args) {
Customer john = new Customer("111", "P_1", "daily",
"create", "table_1", "03-05-2020",
"03-05-2020", "140");
Customer mary = new Customer("111", "P_1", "daily",
"delete", "table_1", "03-05-2020",
"03-05-2020", "30");
Customer joseph = new Customer("222", "P_2", "weekly",
"create", "table_2", "03-05-2020",
"03-05-2020", "50");
Customer jason = new Customer("222", "P_2", "daily",
"update", "table_2", "03-05-2020",
"03-05-2020", "40");
Customer mario = new Customer("111", "P_1", "weekly",
"create", "table_1", "03-05-2020",
"03-05-2020", "20");
Customer danny = new Customer("111", "P_1", "monthly",
"update", "table_1", "03-05-2020",
"03-05-2020", "100");
List<CheckForResource.Customer> customers = Arrays.asList(john, mary, joseph, jason, mario, danny);
}
public static class Customer {
final String Id;
final String pCode;
final String usageType;
final String operation;
final String resource;
final String startTime;
final String endTime;
final String value;
public Customer(String id, String pCode, String usageType, String operation,
String resource, String startTime, String endTime, String value) {
Id = id;
this.pCode = pCode;
this.usageType = usageType;
this.operation = operation;
this.resource = resource;
this.startTime = startTime;
this.endTime = endTime;
this.value = value;
}
}
}
如果列表具有以下每个子句的至少 1 个条目,我想返回 true
- customerId="111", operation="create", usageType="daily"
- customerId="111", operation="create", usageType="monthly"
- customerId="111", operation="delete", usageType="daily"
- customerId="111", operation="delete", usageType="monthly"
- customerId="111", operation="update", usageType="daily"
- customerId="111", operation="update", usageType="monthly"
如何使用 Steam 实现这一点?
【问题讨论】:
-
你的条件可以简化为
"111".equals(customer.getId()) && ("create".equals(customer.getOperation()) || "delete".equals(customer.getOperation())) && ("daily".equals(customer.getUsageType()) || "monthly".equals(customer.getUsageType()))。如果您要创建多个Predicate实例,您仍然可以使用or()组合它们 -
@ernest_k 这个解决方案不起作用列表没有条目,比如说 customerId="111", operation="update", usageType="monthly"
-
我想你错过了我在括号内使用
||这一事实。 -
@ernest_k 我试过这个。如果列表没有第 6 条的条目,则 Predicate
p1 = c -> "111".equals(c.getId()) && ("create".equals(c.getOperation()) || "删除".equals(c.getOperation())) && ("daily".equals(c.getUsageType()) || "monthly".equals(c.getUsageType()));仍然返回 true -
我认为您需要澄清您的问题。我的理解是,如果列表中的至少一个元素满足 6 个条件中的至少一个,您就想返回 true。但是您改为检查每个条件是否由至少一个元素满足。不是很清楚。
标签: java java-stream