Reduce If in Java Stream

Arcones :

How can I apply the reduce operation only if a predicate is true?

For example:

        Stream.of("foo=X","bar=Y","foo=Z")
        .reduce((arg1, arg2)-> arg1.contains(arg2) ? arg1  : <reduceNothing>)
        .collect(Collectors.toList());

I want to get rid of one of "foo=..." to have at the end a list of "foo=X","bar=Y"

Federico Peralta Schaffner :

Here's a way to do it (without streams):

Map<String, String> map = new LinkedHashMap<>();

yourListOfArgs.forEach(arg -> map.merge(arg.split("=")[0], arg, (o, n) -> o));

Collection<String> uniqueArgs = map.values();

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=114813&siteId=1