Преглед на файлове

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 години
родител
ревизия
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
-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
 final class Acronym {
4
 final class Acronym {
5
 
5
 
13
         return acronym;
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
 }