Java中如何实现列表对象(List)的灵活查找?/java中Listgen根据某个元素获取对象

public class Customer {

      private int id;

      private String name;

//其他省略 }

//建立测试数据

List<Customer> customers = new ArrayList<>();

     customers.add(new Customer(1, "Jack"));

     customers.add(new Customer(2, "James"));

     customers.add(new Customer(3, "Kelly"));

//实现查找,找到则返回匹配的对象,找不到则返回null

Customer james = customers.stream() .filter(customer -> "James".equals(customer.getName())) .findAny() .orElse(null);

posted @ 2021-04-21 16:42  编程菜小鸟  阅读(3096)  评论(0编辑  收藏  举报