我有一个整数序列 ( List<Integer>
),并希望将其转换为字符串。我不明白为什么这段代码不起作用:
sequence.stream().map(n -> n == 1 ? "+" : (n == -1 ? "-" : Integer.toString(n))).collect(Collectors.joining(","));
如你所见,我想要1
表示为+
和-1
如-
.
我收到错误消息 Type mismatch: cannot convert from Stream<Object> to <unknown>
.
最佳答案
编辑
读完评论就知道Java没问题了:
Eclipse 不知道n == 1 吗? "+": (n == -1 ? "-": Integer.toString(n))).toString()
是一个字符串。
sequence.stream().map(n -> (String)((n == 1 ? "+" : (n == -1 ? "-" : Integer.toString(n))))).collect(Collectors.joining(","))
工作正常。
编辑
如果将其提取到函数中,Eclipse 就会知道它是一个字符串:
private static String format(Integer n) {
return n == 1 ? "+" : (n == -1 ? "-" : Integer.toString(n));
}
关于java - 将 List<Integer> 转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37627801/