Просмотр исходного кода

Acronym: Simplify model answer

The answer uses Pattern & Matcher to locate each word. This answer works
fine, however, it can be simplified by using String#split(String)
instead with a simpler regex.

Also, let’s add comments for each stream operation to elaborate on
what’s happening at each step of the stream operation.
Zhi Yuan Yong 8 лет назад
Родитель
Сommit
0758847231
1 измененных файлов: 8 добавлений и 10 удалений
  1. 8
    10
      exercises/acronym/.meta/src/reference/java/Acronym.java

+ 8
- 10
exercises/acronym/.meta/src/reference/java/Acronym.java Просмотреть файл

@@ -1,5 +1,5 @@
1
-import java.util.regex.Matcher;
2
-import java.util.regex.Pattern;
1
+import java.util.Arrays;
2
+import java.util.stream.Collectors;
3 3
 
4 4
 final class Acronym {
5 5
 
@@ -13,14 +13,12 @@ final class Acronym {
13 13
         return acronym;
14 14
     }
15 15
 
16
-    private String generateAcronym(String phrase){
17
-        final Pattern BREAK_WORDS = Pattern.compile("[A-Z]+[a-z]*|[a-z]+");
18
-        final Matcher matcher = BREAK_WORDS.matcher(phrase);
19
-        final StringBuilder stringBuilder = new StringBuilder();
20
-        while (matcher.find()){
21
-            stringBuilder.append(matcher.group().charAt(0));
22
-        }
23
-        return stringBuilder.toString().toUpperCase();
16
+    private String generateAcronym(String phrase) {
17
+        return Arrays.stream(phrase.split("[^a-zA-Z]"))
18
+                .filter(word -> !word.isEmpty()) // Remove empty strings from the result of phrase.split
19
+                .map(word -> word.substring(0, 1)) // Get the first character of each word
20
+                .collect(Collectors.joining()) // Concatenate the characters
21
+                .toUpperCase();
24 22
     }
25 23
 
26 24
 }