3

I have a list of Strings and a String. If the String has any of the lists then I need to remove it.

I'm using the below approach and its working fine. I'm just wondering if this can be replaced using Stream API?

List<String> exclude = getExcludeList();

String phrase = "My test phrase";

for (String str: exclude) {
    phrase = phrase.replace(str, "");
}

3 Answers 3

1

You could form a regex alternation consisting of the strings in the list, then do a regex replacement to remove them from the phrase:

List<String> exclude = getExcludeList();
String phrase = "My test phrase";
String regex = exclude.stream().collect(Collectors.joining("|", "\\b(?:", ")\\b"));
phrase = phrase.replaceAll(regex, "");
Sign up to request clarification or add additional context in comments.

1 Comment

To be on the safe side, I’d insert a .map(Pattern::quote). Best answer so far, may even have significant performance advantages for a large number of exclude strings. However, it must be mentioned that it does not have the same semantic, though, in most cases the semantic of this solution is preferable.
0

This will be kind of ugly since you want to modify a non-stream variable inside a stream and stream can only access effectively final variables from outside of their scope.

But it's doable:

String[] holder = new String[] {phrase};

exclude.stream().foreach(s -> phrase[0] = phrase[0].replace(s, "");

Comments

0

In the "Streamy"-Way of Java 8 the best way is to use an reducing Collector:

String phrase = getExcludeList().stream()
    .collect(Collectors.reducing(
        "My test phrase",
        (ph, t) -> ph.replace(t, "")
    ));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.