Search code examples
javastringgenerate

Generate a combination of word list from string


I want to generate a list of keywords from given string in java

e.g. " this is my string"

generated list

"this is my" "this is" "this" "string" "my string" "is my string"


Solution

  • you can try this one:

    public static void main(String[] args) {
        String[] wordArray = "this is my string".split(" ");
        Set<String> result = new HashSet<>();
        int n = wordArray.length;
        for (int i = 0; i < n; i++) {
           for (int j = i; j < n; j++) {
                result.add(
                    IntStream.rangeClosed(i, j)
                        .mapToObj(v -> wordArray[v])
                        .collect(Collectors.joining(" ")));
            }
        }
        result.forEach(System.out::println);
    }
    

    If there is no special rules for input.