我有这个问题想在 java 8 中解决,
我有一个由 连接的字符串。
A.B.C.D
字符串中的字符数可以变化。
我有这个方法,它将字符串作为输入和它必须达到的层数, 我必须循环遍历使用“.”对字符串进行拆分后得到的数字。并进入给定的深度
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
}
这可以在 java 8 中完成吗?
最佳答案
这是 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);
}
如果您确定级别不超过点数,则可以省略检查:
static void getResponseUnsafe(String input, int level) {
Stream.iterate(input, str -> str.substring(0, str.lastIndexOf('.')))
.limit(level + 1).forEach(System.out::println);
}
关于java - Java 8 中的拆分和循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30610173/