首页 > 其他分享 >Stream流anyMatch,allMatch,noneMatch

Stream流anyMatch,allMatch,noneMatch

时间:2023-05-13 12:31:58浏览次数:48  
标签:anyMatch name noneMatch age actor personList allMatch new public

public class Actor {
    private String name;
    private int age;
    private List<Person> personList = new ArrayList<Person>();

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public List<Person> getPersonList() {
        return personList;
    }

    public void setPersonList(List<Person> personList) {
        this.personList = personList;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Actor actor = (Actor) o;
        return age == actor.age &&
                Objects.equals(name, actor.name) &&
                Objects.equals(personList, actor.personList);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, age, personList);
    }

    @Override
    public String toString() {
        return "Actor{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", personList=" + personList +
                '}';
    }
}
static List<Actor> actors = new ArrayList<>();


    private static void initPerson() {
        List<Person> personList1 = new ArrayList<Person>();
        personList1.add(new Person("张三", 8, 3000));
        personList1.add(new Person("李四", 38, 7000));

        Actor actor1 = new Actor();
        actor1.setAge(11);
        actor1.setName("user1");
        actor1.setPersonList(personList1);
        actors.add(actor1);


        List<Person> personList2 = new ArrayList<Person>();
        personList2.add(new Person("孙六", 38, 9000));
        personList2.add(new Person("王五", 28, 7000));
        personList2.add(new Person("李四", 38, 7000));

        Actor actor2 = new Actor();
        actor2.setAge(12);
        actor2.setName("user2");
        actor2.setPersonList(personList2);
        actors.add(actor2);
    }

    public static void main(String[] args) {
        initPerson();
        
        //anyMatch 任意满足就返回true
        boolean b = actors.stream().anyMatch(actor -> actor.getAge() >= 12);
        System.out.println("anyMatch--》"+b);
        //allMatch 都满足才返回true
        boolean all = actors.stream().allMatch(actor -> actor.getAge() >= 12);
        System.out.println("anyMatch--》"+all);
        //noneMatch 都不满足才返回true
        boolean noneMatch = actors.stream().noneMatch(actor -> actor.getAge() >= 12);
        System.out.println("noneMatch--》"+noneMatch);
    }

标签:anyMatch,name,noneMatch,age,actor,personList,allMatch,new,public
From: https://blog.51cto.com/u_16096846/6273669

相关文章