java8 按條件過濾集合

//黃色部分爲過濾條件
list.stream().filter(user-> user.getId() > 5 && "1組".equals(user.group)).collect(Collectors.toList());

示例:dom

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 + '\'' +
                    '}';
        }
    }

}

執行結果:ide

過濾前:[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組'}]
相關文章
相關標籤/搜索