Search code examples
javapredicate

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);
        }
    };
}

Solution

  • 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.