我有一个客户列表对象如下。
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。
我如何使用steams来实现这个功能?
你可以使用 .anyMatch()
Predicate<Customer> p = c -> c.getId().equals("111") &&
(c.getUsageType().equals("daily") || c.getUsageType().equals("monthly")) &&
(c.getOperation().equals("create") || c.getOperation().equals("delete") || c.getOperation().equals("update"));
boolean result = customers.stream().filter(p)
.map(c -> c.getId().concat(c.getOperation()).concat(c.getUsageType())) // Map to create hash string for detect unique
.distinct().count() == 6; // distinct and check the count.
试试这样。
创建一个基于谓词列表的 operation
和 usageType
List<Predicate<String>> preds = toPredicateList(
new String[] { "create", "delete", "update" },
new String[] { "daily", "monthly"});
确定是否满足条件。
boolean result =
customers
.stream()
.filter(c -> c.Id.equals("111"))
.map(c -> c.operation + c.usageType)
.filter(preds.stream().reduce(k -> false,
Predicate::or))
.collect(Collectors.toSet()).size() == 6;
System.out.println(result);
构建谓词列表
public List<Predicate<String>> toPredicateList(String[] ops,
String[] types) {
List<Predicate<String>> list = new ArrayList<>();
for (String o : ops) {
for (String t : types) {
list.add(s -> s.equals(o + t));
}
}
}
return list;
}