邯城往事

>>> 展颜笑夙愿,一笑泯恩仇 <<<

目录
初识java8的函数式编程
/  

初识java8的函数式编程

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class JudgeString {

    public static void main(String[] args) {
        List<String> sourceList = new ArrayList<>();
        sourceList.add("java Spider");
        sourceList.add("java Dolphin");
        sourceList.add("java   ");
        sourceList.add("  java    ");
        sourceList.add("  python    ");
        sourceList.add("  python_2    ");
        sourceList.add("  python_3    ");

        List<String> filterList = new ArrayList<>();
        filterList.add("java");
        filterList.add("python");

        //对sourceList进行过滤,当经过repleceStr方法后可以得到filterList里的任意一个值时,才算合格
        List<String> filter = JudgeString.filter(sourceList, filterList, JudgeString::repleceStr);
        System.out.println(filter);

    }

    public static <K, T> List<T> filter(List<T> sourceList, List<T> filterList, MyProperty<K, T> function){
        return sourceList.stream().filter(item -> {
            K key = function.getKey(item);
            return filterList.stream().anyMatch(y -> y.toString().equals(key.toString()));
        }).collect(Collectors.toList());
    }

    public static String repleceStr(String str){
        return str.replace("Spider", "").replace("Dolphin", "").trim();
    }
}
public interface MyProperty<K, T> {
    K getKey(T t);
}
评论
取消