user3314714
user3314714

Reputation: 19

Efficient way to replace char from each index of a String array if condition match

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

Answers (3)

Eritrean
Eritrean

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

Peter Stoilkov
Peter Stoilkov

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

Ryuzaki L
Ryuzaki L

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

Related Questions