Skip to content
Advertisement

Using a predefined lambda as an argument in Java [closed]

So i’m trying to pass this test:

public void testCountWithCondition() {
        List<Integer> data = Arrays.asList(1, 3, 8, 4, 6);
        int count = streamer.count(data, x -> x % 3 == 0);
        assertEquals(2, count);
    }

I’m having a really hard time understanding how to create a method count that can take the lambda expression as an argument. I’ve seen other posts that say you need to create an interface class but how do I program it to be able to accept any lambda expression? Also, the assignment specifically says I need to use streams. Thanks!

Advertisement

Answer

your method should accept a Predicate. all lambda that take one arg and return boolean implement that interface. invoking the Predicate is done by executing its test() method.

example:

public <T> long count(Collection<T> collection, Predicate<T> filter) {
    return collection.stream()
            .filter(filter)
            .count();
}
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement