-2

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!

Kole Davis
  • 35
  • 4
  • 3
    What is `streamer`? Is it `data.stream()`? – Christoph Dahlen Nov 26 '22 at 18:44
  • 4
    You don't need to make a new interface, you can use one of the existing ones. Look at the definition of `Stream.filter`. – Louis Wasserman Nov 26 '22 at 18:47
  • [Functional interfaces](https://docs.oracle.com/javase/8/docs/api/java/util/function/package-summary.html) (and how to use them in situations like this) may be difficult to grasp. I found [this answer](https://stackoverflow.com/a/28422318/12567365) helpful because of its "_structure not semantics_" insight. – andrewJames Nov 26 '22 at 22:07

1 Answers1

5

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();
}
Sharon Ben Asher
  • 13,849
  • 5
  • 33
  • 47