dre*_*der 0 java string java-stream
例如,当n = 5,我需要生成一个字符串"012345"。
我可以通过for从0to运行循环n并将数字附加到字符串来实现。
for(int i = 0; i <= n; i++) {
s += i;
}
Run Code Online (Sandbox Code Playgroud)
有没有没有for循环的简单方法?也许使用流?
我认为最好的方法是你已经在你的问题中使用循环完成了它。阅读评论,这似乎是普遍的共识。Nikolas Charalambidis在评论中指出,该解决方案可以StringBuilder改为:
StringBuilder s = new StringBuilder();
for(int i = 0; i <= n; i++) {
s.append(i);
}
Run Code Online (Sandbox Code Playgroud)
如果您必须使用 a Stream,我相信接受的答案是要走的路,因为
StringBuilder代替String. 还有其他方法。一种方法是依赖副作用。创建一个变量并从流中更新它。包 java.util.stream上的 JavaDoc警告使用:
通常不鼓励流操作的行为参数的副作用,因为它们通常会导致无意中违反无状态要求,以及其他线程安全危险。
String[] alternativeWayA = {""};
IntStream.rangeClosed(0,n).forEach(i -> alternativeWayA[0] = alternativeWayA[0] + i);
Run Code Online (Sandbox Code Playgroud)
Luiggi Mendoza在一条评论中提到
您可以使用
collect(Collectors.joining())并具有相同的输出
并在另一条评论中
嗯,你可以
boxed在打电话之前使用collect
String alternativeWayB = IntStream.rangeClosed(0,n)
.boxed()
.map(i -> i.toString())
.collect(Collectors.joining(""));
Run Code Online (Sandbox Code Playgroud)
..如果一个人更喜欢使用reduce而不是Collectors.joining:
String alternativeWayC = IntStream.rangeClosed(0,n)
.boxed()
.map(i -> i.toString())
.reduce("", String::concat);
Run Code Online (Sandbox Code Playgroud)
.. 或者正如Nikolas Charalambidis在此评论中所建议的那样
您需要,
mapToObj因为此收集器不可用于IntStream
String alternativeWayD = IntStream.rangeClosed(0,n)
.mapToObj(i -> String.valueOf(i))
.collect(Collectors.joining(""));
Run Code Online (Sandbox Code Playgroud)
String string = new String(IntStream.rangeClosed('1', '1'+n).toArray(), 0, n);
我认为这非常优雅并且适用于n < 10. 因为n = 15结果变成了,0123456789:;<=>?因为它使用字符的整数值。我+ 1在String构造函数的最后一个参数中添加了一个:
String alternativeWayE = new String(IntStream.rangeClosed('0', '0'+n).toArray(), 0, n + 1);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
116 次 |
| 最近记录: |