在java 8中拆分和循环

Use*_*911 5 java split java-8

我有这个问题,我想在java 8中解决,

我有一个串联的字符串 .

A.B.C.D
Run Code Online (Sandbox Code Playgroud)

字符串中的字符数可以变化.

我有这个方法,它将字符串作为输入和它必须去的级别深度,我必须遍历我在使用"."对字符串应用拆分后得到的数字.并且只是给予深度

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
}
Run Code Online (Sandbox Code Playgroud)

这可以在java 8中完成吗?

Tag*_*eev 10

这是Java-8解决方案:

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);
}
Run Code Online (Sandbox Code Playgroud)

如果您确定该级别不超过点数,则可以省略检查:

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


Stu*_*rks 5

不需要循环,因为字符串可以在单个String.split调用中拆分为数组.(注意String.split采用正则表达式.)要处理"级别",只需从拆分数组的长度中减去它.而不是复制数组子范围,将其转换为List并使用subList():

String getResponse(String str, int level) {
    String[] splits = str.split("\\.");
    if (level < 0 || level > splits.length) {
        throw new IllegalArgumentException();
    }
    return String.join(".", Arrays.asList(splits).subList(0, splits.length - level));
}
Run Code Online (Sandbox Code Playgroud)

的输出

    for (int level = 0; level < 5; level++) {
        System.out.printf("level %d: %s%n", level, getResponse("A.B.C.D", level));
    }
Run Code Online (Sandbox Code Playgroud)

将会

level 0: A.B.C.D
level 1: A.B.C
level 2: A.B
level 3: A
level 4: 
Run Code Online (Sandbox Code Playgroud)

请注意,这确实需要Java 8,因为它需要String.join().(但它不需要溪流甚至lambda!)