diff --git a/core-java-modules/core-java-string-operations-4/src/main/java/com/baeldung/split/SplitStringEveryNthChar.java b/core-java-modules/core-java-string-operations-4/src/main/java/com/baeldung/split/SplitStringEveryNthChar.java index 3ac31d012a..0687926cd2 100644 --- a/core-java-modules/core-java-string-operations-4/src/main/java/com/baeldung/split/SplitStringEveryNthChar.java +++ b/core-java-modules/core-java-string-operations-4/src/main/java/com/baeldung/split/SplitStringEveryNthChar.java @@ -3,8 +3,9 @@ package com.baeldung.split; import java.util.ArrayList; import java.util.Arrays; import java.util.List; -import java.util.regex.Matcher; +import java.util.regex.MatchResult; import java.util.regex.Pattern; +import java.util.stream.Collectors; import com.google.common.base.Splitter; import com.google.common.collect.ImmutableList; @@ -29,16 +30,11 @@ public class SplitStringEveryNthChar { } public static List usingPattern(String text, int n) { - List results = new ArrayList<>(); - - Pattern pattern = Pattern.compile(".{1," + n + "}"); - Matcher matcher = pattern.matcher(text); - while (matcher.find()) { - String match = text.substring(matcher.start(), matcher.end()); - results.add(match); - } - - return results; + return Pattern.compile(".{1," + n + "}") + .matcher(text) + .results() + .map(MatchResult::group) + .collect(Collectors.toList()); } public static List usingGuava(String text, int n) {