【如何判断集合中是否有符合条件的元素?】
程序员文章站
2022-06-10 18:36:32
...
工作中常有判断集合中是否存在符合条件的元素的需求,最原始的手段就是使用for循环挨个判断,但是自Java8开始我们有了其它更方便的选项。
public class User {
private String name;
private int age;
public User(String name, int age) {
this.name = name;
this.age = age;
}
public static void main(String[] args) {
List<User> list = new ArrayList<>();
list.add(new User("张三", 29));
list.add(new User("李四", 21));
list.add(new User("王五", 20));
list.add(new User("马六", 22));
User tom = new User("赵七", 23);
// 方法一
// if (!list.stream().filter(o -> o.getAge() == tom.getAge()).findFirst().isPresent()){
// list.add(tom);
// }
// 方法二 noneMatch():根据判断条件,所有元素都不符合,则返回false
// if (list.stream().noneMatch(o -> o.getAge() == tom.getAge())){
// list.add(tom);
// }
// 方法三 allMatch():根据判断条件,所有元素都符合,则返回true
if (list.stream().allMatch(o -> o.getAge() != tom.getAge())){
list.add(tom);
}
System.out.println(list);
}
}
// 运行结果
// [User{name='张三', age=29}, User{name='李四', age=21}, User{name='王五', age=20}, User{name='马六', age=22}, User{name='赵七', age=23}]
推荐阅读
-
JQuery中判断一个元素下面是否有内容或者有某个标签的判断代码
-
【转载】 C#中通过Where方法查找出所有符合条件的元素集合
-
【转载】C#中List集合使用LastOrDefault方法查找出最后一个符合条件的元素
-
【转载】C#中List集合使用Exists方法判断是否存在符合条件的元素对象
-
【转载】 C#中List集合使用First方法查找符合条件的第一个元素
-
Excel2010中如何判断出每行里面是否有重复数据的单元格
-
JQuery中判断一个元素下面是否有内容或者有某个标签的判断代码
-
如何判断一个文件夹中符合判断的所有文件是否全部存在
-
C# 判断List集合中是否有重复的项
-
【如何判断集合中是否有符合条件的元素?】