Unable to figure out the usage

java-8, lambda

Solution

You need to make a new class that implements `Collection2`,

public class ArrayList2<E> extends ArrayList<E> implements Collection2<E>{

}

then just use your new class:

public static void ex09()
{
    Collection2<String> l = new ArrayList2<>();
    l.add("abc");
    l.add("zxx");
    l.add("axc");

    l.forEachIf(  (s)->System.out.println(s.toUpperCase()),
                  (s)-> s.startsWith("a"));


}

Which when run will print:

ABC
AXC

Problem

Following is one of the exercises from Java SE 8 for the Really Impatient. Form a subclass Collection2 from Collection and add a default method void forEachIf(Consumer action, Predicate filter) that applies action to each element for which filter returns true. How could you use it? Following is my definition of `Collection2`. I am unable to figure out how to use it. ``` public interface Collection2<E> extends Collection<E> { default void forEachIf(Consumer<E> action, Predicate<E> filter) { forEach(e -> { if (filter.test(e)) { action.accept(e); } }); } } ``` So, I have the following list that i would like to apply the `String.toUpperCase` action for the strings that start with "a". How would I use `Collection2` to achieve that? ``` public static void ex09() { Collection<String> l = new ArrayList<>(); l.add("abc"); l.add("zxx"); l.add("axc"); // What next??? } ```

Original source