从集合中找出满足条件的元素,apache的CollectionUtils

从集合中找出满足条件的元素,使用apache的CollectionUtils方法中的select方法。据说是涉及到函数式编程。

从集合中找出满足条件的元素,apache的CollectionUtils_第1张图片

package com.bh.apach.collection.test;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.Predicate;

public class CollectionTest2 {

    public CollectionTest2() {
        Test2();
    }
    private void Test2() {

        List list=new ArrayList<>();
        People p1=new People(1,"a");
        People p2=new People(2,"b");
        People p3=new People(3,"c");
        People p4=new People(4,"d");
        People p5=new People(5,"a");
        list.add(p1);
        list.add(p2);
        list.add(p3);
        list.add(p4);
        list.add(p5);
        List list2 = (List) CollectionUtils.select(list, new Predicate() {

            @Override
            public boolean evaluate(People param) {
                if("a".equals(param.getName())){
                    return true;
                }
                return false;
            }
        });
        for(People str:list2){
            System.out.println(str.getId());
        }
    }
    public static void main(String[] args) {
        new CollectionTest2();
    }
    class People {
        private int id;
        private String name;
        public People(int id, String name) {
            super();
            this.id = id;
            this.name = name;
        }
        public int getId() {
            return id;
        }
        public void setId(int id) {
            this.id = id;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }

    }
}

你可能感兴趣的:(java)