如题:list中存放的beans,想知道这些beans中的某个字段是否存在于里面,按照原来的操作是需要遍历list拿出逐个bean进行字段的equals,现在使用lamda表达式的话可以简化代码,如下:
1 |
boolean isExsists = list.stream().anyMatch(a -> a.getName().equals("aaa")); |
代码示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
package com.owl.demo.tests; import java.util.ArrayList; import java.util.List; public class LamdaTest { public static void main(String[] args) { //示例数据 People p1 = new People(); p1.setName("aaa"); p1.setAge(23); People p2 = new People(); p2.setName("bbb"); p2.setAge(23); People p3 = new People(); p3.setName("ccc"); p3.setAge(23); List<People> list = new ArrayList<People>(); list.add(p1); list.add(p2); list.add(p3); //lamda判断list中是否存在name=aaa的对象 boolean isExsists = list.stream().anyMatch(a -> a.getName().equals("aaa")); System.out.println(isExsists); } } |
from:https://blog.csdn.net/csdn_avatar_2019/article/details/123704052