gpt4 book ai didi

java-8 - 如何在Java 8+中将范围转换为定界字符串

转载 作者:行者123 更新时间:2023-12-04 05:45:42 25 4
gpt4 key购买 nike

如何将Java中的范围(使用java.util.stream.LongStreamjava.util.stream.IntStream)转换为Java中的定界字符串?

我试过了:

String str = LongStream.range(16, 30)
.boxed()
.map(String::valueOf)
.collect(Collectors.joining(","));
System.out.println(str);

打印:
16,17,18,19,20,21,22,23,24,25,26,27,28,29

可以与 IntStream一起使用。将范围转换为带分隔符的字符串是否更方便?

最佳答案

认真地说,只是为了好玩。使用 Guava :

String result = ContiguousSet.create(
Range.closedOpen(16, 31), DiscreteDomain.integers())
.asList()
.toString();

或者
 String result = String.join(",",
IntStream.rangeClosed(16, 30).mapToObj(String::valueOf).toArray(String[]::new));

或者:
String result = String.join(",",
() -> IntStream.rangeClosed(16, 31).mapToObj(x -> (CharSequence) String.valueOf(x)).iterator());

或(似乎我对此有些迷惑):
String result = IntStream.rangeClosed(16, 31)
.boxed()
.collect(
Collector.of(
() -> new Object() {
StringBuilder sb = new StringBuilder();
},
(obj, i) -> obj.sb.append(i).append(",")
,
(left, right) -> {
left.sb.append(right.sb.toString());
return left;
},
x -> {
x.sb.setLength(x.sb.length() - 1);
return x.sb.toString();
})
);

根据Holger的观点,这是一个更简单的版本:
    StringBuilder sb = IntStream.range(16, 30)
.collect(
StringBuilder::new,
(builder, i) -> builder.append(i).append(", "),
StringBuilder::append);

if (sb.length() != 0) {
sb.setLength(sb.length() - 2);
}
String result = sb.toString();

关于java-8 - 如何在Java 8+中将范围转换为定界字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50406260/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com