【Java】利用Predicate实现条件筛选

package LearnJava21;

import java.util.ArrayList;
import java.util.function.Predicate;

public class PredicateDemo02 {
    public static void main(String[] args) {
        /*
        *将姓名长度大于2,年龄大于20的人筛选出来
        *
        * */
        String[] strArray={"诸葛亮,25","刘备,21","鲁智深,19","及时雨,23","孙悟空,22"};
        ArrayList<String> array = myFilter(strArray, s -> s.split(",")[0].length() > 2,
                s -> Integer.parseInt(s.split(",")[1]) > 20);
        for (String str:array){
            System.out.println(str);
        }
    }
    private static ArrayList<String> myFilter(String[] strArray, Predicate<String> pre1,Predicate<String> pre2){
        ArrayList<String> array = new ArrayList<>();
//        遍历数组
        for (String str:strArray){
            if (pre1.and(pre2).test(str)){
                array.add(str);
            }
        }
        return array;
    }
}

posted @ 2022-05-06 09:59  木子欢儿  阅读(206)  评论(0编辑  收藏  举报