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 !
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.
text = toRemove.stream()
.reduce(text, (str, toRem) -> str.replaceAll(toRem, ""));
would work for you.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With