Reputation: 179
I'm solving the problem where I must find the longest string in the list and replace all other list items with that string:
The longest string in the list
Inside the given method you should:
1. find the longest string in the list 2. replace all list items with the found string
When I use regular expression "\\w+"
the method does not work:
Collections.replaceAll(list, "\\w+", longestString);
When I replace the specific words by specifying them in a method argument - all works properly, e.g.:
Collections.replaceAll(list, "word", longestString);
Why is that? Where is my error?
Upvotes: 1
Views: 328
Reputation: 3866
Collections.replaceAll
method does not support Regex. Probably you should use List.replaceAll
method:
list.replaceAll(e -> longestString);
Here is the working example:
// Dummy Values
List<String> list = new ArrayList<>();
list.add("Hey");
list.add("World");
list.add("Bye");
String longestString = "World";
// Replacing every word with `longestString`
list.replaceAll(e -> longestString);
// Printing
System.out.println(list);
Output:
[World, World, World]
Upvotes: 1