Java – Split and Loop in java 8

javajava-8split

I have this problem which I want to solve in java 8,

I have a string which is concatenated by .

A.B.C.D

Number of characters in the string can vary.

I have this method, which takes the string as input and number of level deep it has to go,
I have to loop through the number that i get after applying a split on string with "." and go just given level deep

private String getResponse (String str, int level) {
// for now, simply print the entire string first and then start removing last alphabet of it one by one till the value of level
// ex : str = A.B.C.D
// System.out.println("Doing a call with key as = " + str); => should give me A.B.C.D
// Apply logic of split 
// System.out.println("Doing a call with key as = " + str); => should give me A.B.C
// Split again
// System.out.println("Doing a call with key as = " + str); => should give me A.B
// this should go in loop till we reach the level
}

Can this be done in java 8?

Best Solution

Here's Java-8 solution:

static void getResponse(String input, int level) {
    Stream.iterate(input, str -> {
        int pos = str.lastIndexOf('.');
        return pos == -1 ? "" : str.substring(0, pos);
    }).limit(level+1).forEach(System.out::println);
}

If you know for sure that level does not exceed the number of dots, you can omit the check:

static void getResponseUnsafe(String input, int level) {
    Stream.iterate(input, str -> str.substring(0, str.lastIndexOf('.')))
            .limit(level + 1).forEach(System.out::println);
}