Java8集合过滤操作

首先准备实体类

package entity;

public class Person {

    private Integer age;
    private String name;

    public Person(Integer age, String name) {
        this.age = age;
        this.name = name;
    }

    public Person() {
    }

    public Integer getAge() {
        return age;
    }

    public Person setAge(Integer age) {
        this.age = age;
        return this;
    }

    public String getName() {
        return name;
    }

    public Person setName(String name) {
        this.name = name;
        return this;
    }

    @Override
    public String toString() {
        return "Person{" +
                "age=" + age +
                ", name='" + name + '\'' +
                '}';
    }
}

然后准备集合数据

		String nameStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

        List<Person> people = new ArrayList<>();
        for (int i = 0; i < nameStr.length(); i++) {
            Person person = new Person(i,nameStr.substring(i));
            people.add(person);
        }

测试一:
筛选所有年龄余2为0的数据

        List<Person> ageList = people.stream().filter(person -> person.getAge() % 2 == 0).collect(Collectors.toList());
        ageList.forEach(System.out::println);

结果

Person{age=0, name='ABCDEFGHIJKLMNOPQRSTUVWXYZ'}
Person{age=2, name='CDEFGHIJKLMNOPQRSTUVWXYZ'}
Person{age=4, name='EFGHIJKLMNOPQRSTUVWXYZ'}
Person{age=6, name='GHIJKLMNOPQRSTUVWXYZ'}
Person{age=8, name='IJKLMNOPQRSTUVWXYZ'}
Person{age=10, name='KLMNOPQRSTUVWXYZ'}
Person{age=12, name='MNOPQRSTUVWXYZ'}
Person{age=14, name='OPQRSTUVWXYZ'}
Person{age=16, name='QRSTUVWXYZ'}
Person{age=18, name='STUVWXYZ'}
Person{age=20, name='UVWXYZ'}
Person{age=22, name='WXYZ'}
Person{age=24, name='YZ'}

测试二:
筛选所有名字中含有”H“的数据

        List<Person> nameList = people.stream().filter(person -> person.getName().contains("H")).collect(Collectors.toList());
        nameList.forEach(System.out::println);

结果

Person{age=0, name='ABCDEFGHIJKLMNOPQRSTUVWXYZ'}
Person{age=1, name='BCDEFGHIJKLMNOPQRSTUVWXYZ'}
Person{age=2, name='CDEFGHIJKLMNOPQRSTUVWXYZ'}
Person{age=3, name='DEFGHIJKLMNOPQRSTUVWXYZ'}
Person{age=4, name='EFGHIJKLMNOPQRSTUVWXYZ'}
Person{age=5, name='FGHIJKLMNOPQRSTUVWXYZ'}
Person{age=6, name='GHIJKLMNOPQRSTUVWXYZ'}
Person{age=7, name='HIJKLMNOPQRSTUVWXYZ'}
已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 数字20 设计师:CSDN官方博客 返回首页