//黄色部分为过滤条件
list.stream().filter(user-> user.getId() > 5 && "1组".equals(user.group)).collect(Collectors.toList());
示例:
public class HelloWorld { public static void main(String[] args) { Random random = new Random(); List<User> list = new ArrayList<>(); for(int i=1;i<=20;i++) { String group = (random.nextInt(3) + 1) + "组";//1-3组随机 User u = new User(i, "用户-" + i, group); list.add(u); } System.out.println("过滤前:" + list); //按条件过滤 List<User> filterList = list.stream().filter(user -> user.getId() > 5 && "1组".equals(user.group)).collect(Collectors.toList()); System.out.println("过滤 后:" + filterList); } private static class User{ Integer id; String name; String group; public User(Integer id, String name, String group) { this.id = id; this.name = name; this.group = group; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getGroup() { return group; } public void setGroup(String group) { this.group = group; } @Override public String toString() { return "User{" + "id=" + id + ", name='" + name + '/'' + ", group='" + group + '/'' + '}'; } } }
执行结果:
过滤前:[User{id=1, name='用户-1', group='2组'}, User{id=2, name='用户-2', group='1组'}, User{id=3, name='用户-3', group='2组'}, User{id=4, name='用户-4', group='2组'}, User{id=5, name='用户-5', group='3组'}, User{id=6, name='用户-6', group='1组'}, User{id=7, name='用户-7', group='3组'}, User{id=8, name='用户-8', group='2组'}, User{id=9, name='用户-9', group='1组'}, User{id=10, name='用户-10', group='1组'}, User{id=11, name='用户-11', group='2组'}, User{id=12, name='用户-12', group='2组'}, User{id=13, name='用户-13', group='2组'}, User{id=14, name='用户-14', group='2组'}, User{id=15, name='用户-15', group='2组'}, User{id=16, name='用户-16', group='3组'}, User{id=17, name='用户-17', group='1组'}, User{id=18, name='用户-18', group='1组'}, User{id=19, name='用户-19', group='1组'}, User{id=20, name='用户-20', group='3组'}]
过滤 后:[User{id=6, name='用户-6', group='1组'}, User{id=9, name='用户-9', group='1组'}, User{id=10, name='用户-10', group='1组'}, User{id=17, name='用户-17', group='1组'}, User{id=18, name='用户-18', group='1组'}, User{id=19, name='用户-19', group='1组'}]
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/16937.html