Reputation: 19
I'm looking for efficient way to replace specific char from a list of email addresses if the char matches in any index of the array. But it should return the full array list.
my current code:
List<String> emailList = new ArrayList<>();
emailList.addAll(Arrays.asList("[email protected]","[email protected]","[email protected]"));
List<String> updatedEmail = emailList.stream().filter(a->a.contains("+")).
map(s -> s.replaceAll("\\+", ""))
.collect(Collectors.toList());
emailList.stream().filter(a->!a.contains("+")).forEach(b->updatedEmail.add(b));
updatedEmail.stream().forEach(b->System.out.println("email: "+b));
Console:
email: [email protected]
email: [email protected]
email: [email protected]
Upvotes: 0
Views: 173
Reputation: 16498
In case you want to modify the original list without using streams and creating a new list, you can do something like:
emailList.replaceAll(s -> s.replace("+", ""));
Upvotes: 1
Reputation: 11
You already use replaceAll
method and you can directly modify every element in current list and print it with foreach
.
emailList.stream()
.map(s -> s.replaceAll("\\+", ""))
.forEach(b -> System.out.println("email: " + b));
Upvotes: 0
Reputation: 40078
You can use replaceAll
on all strings and string not having +
symbol will remains unchanged
List<String> updatedEmail = emailList.stream()
.map(s -> s.replaceAll("\\+", ""))
.collect(Collectors.toList());
Upvotes: 1