gpt4 book ai didi

java - 将整数流连接到字符串,类型转换问题

转载 作者:搜寻专家 更新时间:2023-10-31 08:26:24 25 4
gpt4 key购买 nike

我正在尝试使用流将一个整数数组连接到一个字符串中(例如 {1, 2, 3} -> "1, 2, 3"),但我不断收到编译错误。 int/String 类型转换似乎有问题。

数组是 int[] IntArray = {1, 2, 3, 4}

    String s1 = Arrays.stream(IntArray)
.map(String::valueOf)
.collect(Collectors.joining(", "));

给出一个编译错误:

Error:(20, 68) java: incompatible types: bad return type in lambda expression
java.lang.String cannot be converted to int

.map(Object::toString).map(n -> Integer.toString(n)) 替换 map 行也不起作用:

Error:(23, 49) java: incompatible types: invalid method reference
method toString in class java.lang.Object cannot be applied to given types
required: no arguments
found: int
reason: actual and formal argument lists differ in length

.map(Object::toString),第一个错误是.map(n -> Integer.toString(n))

最佳答案

你需要使用:

int[] intArray = {1, 2, 3, 4};
String s1 = Arrays.stream(intArray)
.mapToObj(String::valueOf)
.collect(Collectors.joining(", "));

这里有一个细微的区别,这是非常重要的:

mapToObj(String::valueOf)

我映射 IntStreamStream<String>在这里,如果你使用常规的 map方法,那么它只需要一个 IntUnaryOperator因此你必须留在int内.

关于java - 将整数流连接到字符串,类型转换问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22533772/

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