Java 8 lambda predicate chaining?

前端 未结 6 1686
渐次进展
渐次进展 2020-12-08 19:30

I can\'t get it to compile, is it even possible to chain predicate lambdas?

Arrays.asList(\"1\",\"2\",\"3\").stream().filter( (e -> e==\"1\" ).or(e-> e         


        
6条回答
  •  离开以前
    2020-12-08 19:48

    I was working on a similar problem of predicate chaining and came up with the following

    public static  Predicate chain (Function> mapFn, T[]args) {
        return Arrays.asList(args)
            .stream()
            .map(x->mapFn.apply(x))
            .reduce(p->false, Predicate::or);
    }
    

    The first parameter to chain is a lambda (Function) that returns a lambda (Predicate) so it needs a couple of arrows

    public static void yourExample() {
        String[] filterVals = { "1", "2" };
    
        Arrays.asList("1","2","3")
            .stream()
            .filter(chain(x-> (y-> y.equals(x)), filterVals))
            .count();
    }
    

    For comparison, here is what I was trying to achieve...

    public static void myExample() {
        String[] suffixes = { ".png", ".bmp" };
        Predicate p = chain (x-> y-> y.endsWith(x), suffixes);
        File[] graphics = new File("D:/TEMP").listFiles((dir,name)->p.test(name));
        Arrays.asList(graphics).forEach(System.out::println);
    }
    

提交回复
热议问题