简体   繁体   中英

Reduce If in Java Stream

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"

Just use a merger that would get the first (in encounter order) result in case a duplicate is found:

Collection<String> result = Stream.of("foo=X", "bar=Y", "foo=Z", "bar=M", "test=12")
            .collect(Collectors.toMap(
                    x -> x.split("=")[0],
                    Function.identity(),
                    (left, right) -> left,
                    LinkedHashMap::new))
            .values();

    System.out.println(result); // [foo=X, bar=Y, test=12]

I've used LinkedHashMap in case you need to preserve the initial order, if you don't need that, simply use:

 Collection<String> result = Stream.of("foo=X", "bar=Y", "foo=Z", "bar=M", "test=12")
            .collect(Collectors.toMap(
                    x -> x.split("=")[0],
                    Function.identity(),
                    (left, right) -> left))
            .values();

  System.out.println(result); // [bar=Y, test=12, foo=X]

Try this:

Stream.of("foo=X","bar=Y","foo=Z")
            .collect(Collectors.toMap(
                    x -> getLeftSide(x),
                    x -> x,
                    (x, y) -> x
            ))
            .values();

I assume that you have getLeftSide method that returns left part of assignment (convert "foo=bar" to "foo" ).

If there is flexibility to use any other operation other than reduce then following could be answer:

@Test
public void test(){
    System.out.println(methodContainingFilteringLogic(word -> word.equals("foo=Z"),
            Stream.of("foo=X","bar=Y","foo=Z")));
}

public static List<String> methodContainingFilteringLogic(Predicate<String> predicate, Stream<String> wordsStream) {
    return wordsStream.filter(word -> predicate.negate().test(word))
            .collect(Collectors.toList());
}

In your case, it would be known at point on which basis given stream should be filtered. At that point methodContainingFilteringLogic could be invoked.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM