java8 Predicate源码学习

原创
2017/03/16 17:02
阅读数 69

看别人写的用法真蛋疼。

主要自己定义Predicate的与或运算

code

public Predicate mypredicateand(Predicate predicate1, Predicate predicate2) {
        Objects.requireNonNull(predicate2);
        return (x) -> predicate1.test(x) && predicate2.test(x);
    }

    public Predicate mypredicateor(Predicate predicate1, Predicate predicate2) {
        Objects.requireNonNull(predicate2);
        return (x) -> predicate1.test(x) || predicate2.test(x);
    }

test

  @Test
    public void testMyPredicateand() {
        Predicate<String> predicate1 = new Predicate<String>() {
            @Override
            public boolean test(String o) {
                return o.length() >= 5;
            }
        };
        Predicate<String> predicate2 = new Predicate<String>() {
            @Override
            public boolean test(String s) {
                return s.length() <= 7;
            }
        };
        Predicate<String> predicate = mypredicateand(predicate1, predicate2);
        List<String> list = new ArrayList<>();
        list.add("a");
        list.add("OTHKJ");
        list.add("12345678");
        list.add("12345");
        list.add("123876533");
        list.add("123");
        System.out.println(list);
        Object[] result = list.stream().filter(predicate).toArray();
        for (Object obj : result)
            System.out.println(obj);
    }

    @Test
    public void testMyPredicateor() {
        Predicate<String> predicate1 = new Predicate<String>() {
            @Override
            public boolean test(String o) {
                return o.length() < 5;
            }
        };
        Predicate<String> predicate2 = new Predicate<String>() {
            @Override
            public boolean test(String s) {
                return s.length() > 7;
            }
        };
        Predicate<String> predicate = mypredicateor(predicate1, predicate2);
        List<String> list = new ArrayList<>();
        list.add("a");
        list.add("OTHKJ");
        list.add("12345678");
        list.add("12345");
        list.add("123876533");
        list.add("123");
        System.out.println(list);
        Object[] result = list.stream().filter(predicate).toArray();
        for (Object obj : result)
            System.out.println(obj);
    }

result

[a, OTHKJ, 12345678, 12345, 123876533, 123]
OTHKJ
12345
[a, OTHKJ, 12345678, 12345, 123876533, 123]
a
12345678
123876533
123
展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部