Home > Software design >  Group java string based on nth word in Camel case
Group java string based on nth word in Camel case

Time:11-22

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

CodePudding user response:

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);
  • Related