Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 Stream - How to return replace a strings contents with a list of items to find

I wish to replace the code below using java8 .stream() or .foreach(). However I am having trouble doing this.

Its probably very easy, but I'm finding the functional way of thinking a struggle :)

I can iterate, no problem but the but returning the modified string is the issue due to mutability issues.

Anyone have any ideas ?

List<String> toRemove = Arrays.asList("1", "2", "3");
String text = "Hello 1 2 3";

for(String item : toRemove){
    text = text.replaceAll(item,EMPTY);
}

Thanks !

like image 731
SteveG Avatar asked Jun 03 '14 09:06

SteveG


People also ask

How do I replace a String in a List with another String in Java?

Create a new ArrayList. Populate the list with elements, with the add(E e) API method of the ArrayList. Invoke the replaceAll(List list, Object oldVal, Object newVal) API method of the Collections. It will replace all occurrences of the specified element from the list with the new provided element.


2 Answers

text = toRemove.stream()
               .reduce(text, (str, toRem) -> str.replaceAll(toRem, ""));

would work for you.

like image 136
yuba Avatar answered Nov 16 '22 03:11

yuba


Since you can’t use the stream to modify the text variable you have to coerce the operation into one Function which you can apply to the text to get the final result:

List<String> toRemove = Arrays.asList("1", "2", "3");
String text = "Hello 1 2 3";
text=toRemove.stream()
             .map(toRem-> (Function<String,String>)s->s.replaceAll(toRem, ""))
             .reduce(Function.identity(), Function::andThen)
             .apply(text);
like image 27
Holger Avatar answered Nov 16 '22 03:11

Holger