I want to group certain java strings into subset of strings with same nth word.
Eg List:
CorePlatformPortal, CorePlatformRuntime, CorePlatformRuntimeConfiguration, DetailPageAlternative, DetailPageBooks, DetailBuild, HorizontePage, HorizontePageLogging, HorizonteBuild,
Input : 1
Output:
CorePlatformPortal, CorePlatformRuntime, CorePlatformRuntimeConfiguration || DetailPageAlternative, DetailPageBooks, DetailBuild || HorizontePage, HorizontePageLogging, HorizonteBuild
Explanation- Grouped based on Core, Detail, Horizonte
Input : 2
Output:
CorePlatformPortal, CorePlatformRuntime, CorePlatformRuntimeConfiguration || DetailPageAlternative, DetailPageBooks, HorizontePage, HorizontePageLogging || DetailBuild, HorizonteBuild
Explanation- Grouped based on Platform, Page, Build
Any leads are appreciated. Thanks
Advertisement
Answer
You can make grouping using Stream API and splitting initial strings into array of words using Regexp:
List<String> list = Arrays.asList("CorePlatformPortal", "CorePlatformRuntime", "CorePlatformRuntimeConfiguration", "DetailPageAlternative", "DetailPageBooks", "DetailBuild", "HorizontePage", "HorizontePageLogging", "HorizonteBuild"); int input = 2; Map<String, List<String>> output = list.stream() .collect(Collectors.groupingBy(str -> str.split("(?=[A-Z])")[input-1])); System.out.println(output);