0

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]
2
  • Note that s.replace("+", "") is better than replaceAll as it avoids regex each call so it is just emailList.stream().map(s -> s.replace("+", "")).forEach(System.out::println) or emailList.stream().map(s -> s.replace("+", "")).toList() Commented Jul 27, 2022 at 8:56
  • 1
    Note that for Gmail addresses, emailadress [email protected] refers to just [email protected], so the suffix behind the + can be used as label. However, they're not the same as [email protected], which would be the result of your string replacement. Commented Jul 27, 2022 at 9:08

3 Answers 3

1

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());
Sign up to request clarification or add additional context in comments.

Comments

1

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("+", ""));

Comments

0

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

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.