Unable to determine usage

The following is one of the exercises from Java SE 8 for Really Impatient.

Subclass Collection2 from the collection and add the default method void forEachIf (user action, predicate filter), which applies the action to each element for which the filter returns true. How could you use it?

The following is my definition Collection2. I can’t 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 to the action String.toUpperCasefor lines starting with "a". How to use Collection2to achieve this?

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

        // What next???

}
+4
source share
1 answer

, Collection2,

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

}

:

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


}

:

ABC
AXC
+6

Source: https://habr.com/ru/post/1548353/


All Articles