From 2e4b518c4b039d0480bd5a25d50714e9d1956691 Mon Sep 17 00:00:00 2001 From: Azhwani <13301425+azhwani@users.noreply.github.com> Date: Sun, 20 Mar 2022 15:19:29 +0100 Subject: [PATCH] improve split string using pattern (#11945) --- .../split/SplitStringEveryNthChar.java | 18 +++++++----------- 1 file changed, 7 insertions(+), 11 deletions(-) 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) {