简体   繁体   English

Java 6 guava谓词到Java 8谓词和Lambda

[英]Java 6 guava Predicate to Java 8 Predicate & Lambda

I have been developing in Java 6 and using guava predicates. 我一直在使用Java 6进行开发并使用guava谓词。 But I want to switch to Java 8 and use java util predicates instead. 但是我想切换到Java 8并改用Java util谓词。 I can simply convert the below method to use the predicate but is there a smart way to use Lambda expressions and reduce the number of lines of code ? 我可以简单地将以下方法转换为使用谓词,但是有没有使用Lambda表达式并减少代码行数的聪明方法? Preferably remove the temp list I am creating ? 最好删除我要创建的临时列表? I am googling for examples but all of them are very simple ones. 我正在搜索示例,但所有示例都是非常简单的示例。 Thanks for you help! 感谢您的帮助!

    private Predicate<Objt1> getLocalAttributesPredicate() {
    return new Predicate<Objt1>() {

        @Override
        public boolean apply(Objt1 input) {

            AttributeType attr = cache.get(input.getAttributeID());
            List<String> attrGroupids = Lists.newArrayList();
            for (AttributeGroupLinkType group : attr.getAttributeGroupLink()) {
                attrGroupids.add(group.getAttributeGroupID());
            }
            return attrGroupids.contains(localAttrGroupId) && !attrGroupids.contains(exclustionAttrGroupId);
        }
    };
}

Something like the following: 类似于以下内容:

private Predicate<Objt1> getLocalAttributesPredicate() {
    return input -> cache.get(input.getAttributeID())
            .stream()
            .map(group -> group.getAttributeGroupID())
            .filter(id -> id.equals(localAttrGroupId))
            .filter(id -> !id.equals(exclustionAttrGroupId))
            .limit(1)
            .count() > 0;
}

So the predicate is returned as a lambda function, and it utilises the Stream API to traverse the list and convert its contents. 因此,谓词作为lambda函数返回,并且它利用Stream API遍历列表并转换其内容。

Edit: applied the optimisation suggested by @Aominè, thanks. 编辑:应用了@Aominè建议的优化,谢谢。

This is how you'd do it as of Java-8: 从Java-8开始,这是您的处理方式:

private Predicate<Objt1> getLocalAttributesPredicate() {
   return input ->  { 
         Set<String> accumulator = ...
         AttributeType attr = cache.get(input.getAttributeID());
         for(AttributeGroupLinkType group : attr.getAttributeGroupLink())
              accumulator.add(group.getAttributeGroupID());
         return accumulator.contains(localAttrGroupId) &&
                !accumulator.contains(exclustionAttrGroupId);
   };
}

Note, that I've also used a Set for the accumulator as the Contains method is much faster for a Set implementation than for a List implementation. 请注意,我还使用了Set作为累加器,因为Set实现的Contains方法比List实现快得多。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM