我有一个 Person 类:
@Data
public class Person {
private Integer id;
private String status;
}
我有一个名为 personList 的人员列表:
[{
"id": null,
"status": "inactive"
},
{
"id": 2,
"status": "inactive"
},
{
"id": null,
"status": "active"
}]
现在我需要找到所有状态为“不活跃”的人,无论此人是否有 ID。如果某人没有 Id,但状态为“活跃”,则也包括该人。我正在使用 Java 流进行过滤:
List<Person> inactivePersonList =
personList.stream()
.filter(person -> person.getStatus().equals("inactive"))
.filter(person -> person.getId() == null && person.getStatus().equals("active"))
.collect(Collectors.toList());
流式传输后的结果是没有人接听。第一个人因为没有通过第二个过滤器而没有被捡到,最后一个人因为没有通过第一个过滤器而没有被捡到。
我想我可以通过使用 OR
将两个过滤器组合成一个来修复它,但我试图让每个过滤器都简单,所以在我做出改变之前,我想问一下是否有是一种更好的方法。谢谢。
最佳答案
过滤器是附加的。它们有效地被 &&
组合在一起。当您需要 ||
时,长过滤器是不可避免的。
List<Person> inactivePersonList =
personList.stream()
.filter(p -> p.getStatus().equals("inactive") ||
p.getId() == null && p.getStatus().equals("active"))
.collect(Collectors.toList());
如果您有单独的 Predicate
对象,您可以将它们.or()
在一起。
Predicate<Person> inactive = p -> p.getStatus().equals("inactive");
Predicate<Person> activeUnknown = p -> p.getId() == null && p.getStatus().equals("active");
List<Person> inactivePersonList =
personList.stream()
.filter(inactive.or(activeUnknown))
.collect(Collectors.toList());
甚至:
Predicate<Person> inactive = p -> p.getStatus().equals("inactive");
Predicate<Person> unknown = p -> p.getId() == null;
Predicate<Person> active = p -> p.getStatus().equals("active");
List<Person> inactivePersonList =
personList.stream()
.filter(inactive.or(unknown.and(active)))
.collect(Collectors.toList());
关于Java Stream 过滤相同的字段但不同的标准,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60550754/