简体   繁体   中英

Java 6 guava Predicate to Java 8 Predicate & Lambda

I have been developing in Java 6 and using guava predicates. But I want to switch to Java 8 and use java util predicates instead. 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 ? 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.

Edit: applied the optimisation suggested by @Aominè, thanks.

This is how you'd do it as of 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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