Is it possible to add an entry to removeIf in java 8?

I am using Java 8.

The following code works fine:

public void testMethod(List<String> prop1, EmailJson randomModel) {
    prop1.stream().forEach(s -> randomModel.getSomeList()
            .removeIf(model -> model.getSomeProp().equalsIgnoreCase(s)));
}

Is it possible to register a message if the condition is true?

I am looking for something similar to:

public void testMethod(List<String> prop1, EmailJson randomModel) {
    prop1.stream().forEach(s -> randomModel.getSomeList()
            .removeIf(model -> model.getSomeProp().equalsIgnoreCase(s))
                    - > if this is true then log some action);
}
+4
source share
2 answers

If this is a recurring problem, you can create a helper method that generalizes the task of decorating a predicate with another action, for example. logging:

static <T> Predicate<T> logging(Predicate<T> p, BiConsumer<T,Boolean> log, boolean all) {
    return t -> {
        final boolean result = p.test(t);
        if(all || result) log.accept(t, result);
        return result;
    };
}

which you can use as

public void testMethod(List<String> prop1, EmailJson randomModel){
    prop1.forEach(s -> randomModel.getSomeList()
        .removeIf(logging(model -> model.getSomeProp().equalsIgnoreCase(s),
            (model,b) -> LOGGER.info(() -> "matched: "+model.getSomeProp()), false)));
}

although in this particular case, it may not be necessary to decorate the predicate itself, since it removeIfreturns a boolean, indicating whether matches have been deleted, and the match value is still in scope:

public void testMethod(List<String> prop1, EmailJson randomModel){
    prop1.stream().forEach(s -> {
        if(randomModel.getSomeList()
                      .removeIf(model -> model.getSomeProp().equalsIgnoreCase(s)))
            LOGGER.info(() -> "there were matches of: "+s);
    });
}
+5

removeIf(model -> model.getSomeProp().equalsIgnoreCase(s))

removeIf(model -> {
                    boolean ret = model.getSomeProp().equalsIgnoreCase(s);
                    if (ret) {
                        // add logging
                    }
                    return ret;
                  })
+5

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


All Articles