使用Java 8将长整型列表转换为整数可迭代对象

5
我该如何将一个长整型列表转换为整数列表?我写的代码是:
longList.stream().map(Long::valueOf).collect(Collectors.toList())
//longList is a list of long.

我有一个错误:

Incompatible types. Required iterable<integer> but collect was inferred to R.

请问有谁知道如何修复这个问题吗?


6
为什么你会期望.map(Long::valueOf)将长整型转换成整型? - shmosel
注意:.map 返回一个对象,因此当您调用 Long.ValueOf 时,它将自动将其装箱为 long,创建一个新对象(除非缓存)。 - Peter Lawrey
2个回答

11
你需要使用 Long::intValue 而不是 Long::valueOf,因为该函数返回的是 Long 类型而不是 int
Iterable<Integer> result = longList.stream()
                                   .map(Long::intValue)
                                   .collect(Collectors.toList());

或者如果您希望接收器类型为List<Integer>

List<Integer> result = longList.stream()
                               .map(Long::intValue)
                               .collect(Collectors.toList());

2

如果您不关心溢出或下溢,可以使用 Long::intValue。但是,如果您希望在发生此情况时抛出异常,则可以执行以下操作:

Iterable<Integer> result = 
    longList.stream()
            .map(Math::toIntExact) // throws ArithmeticException on under/overflow
            .collect(Collectors.toList());

如果您希望“饱和”该值,可以进行如下操作:
Iterable<Integer> result = 
    longList.stream()
            .map(i -> (int) Math.min(Integer.MAX_VALUE, 
                                     Math.max(Integer.MIN_VALUE, i)))
            .collect(Collectors.toList());

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接