本文翻译自:How to convert List to int[] in Java? [duplicate]
This question already has an answer here: 这个问题已经在这里有了答案:
This is similar to this question: How to convert int[] to Integer[] in Java? 这类似于以下问题: 如何在Java中将int []转换为Integer []?
I'm new to Java. 我是Java新手。 How can i convert a List<Integer>
to int[]
in Java? 如何在Java中将List<Integer>
转换为int[]
? I'm confused because List.toArray()
actually returns an Object[]
, which can be cast to nether Integer[]
or int[]
. 我很困惑,因为List.toArray()
实际上返回一个Object[]
,可以将其List.toArray()
为Integer[]
或int[]
。
Right now I'm using a loop to do so: 现在,我正在使用循环来做到这一点:
int[] toIntArray(List<Integer> list){
int[] ret = new int[list.size()];
for(int i = 0;i < ret.length;i++)
ret[i] = list.get(i);
return ret;
}
I'm sure there's a better way to do this. 我敢肯定有更好的方法可以做到这一点。
#1楼
参考:https://stackoom.com/question/41qp/如何转换清单-Integer-Java中的int-重复
#2楼
Using a lambda you could do this (compiles in jdk lambda): 使用lambda可以做到这一点(在jdk lambda中编译):
public static void main(String ars[]) {
TransformService transformService = (inputs) -> {
int[] ints = new int[inputs.size()];
int i = 0;
for (Integer element : inputs) {
ints[ i++ ] = element;
}
return ints;
};
List<Integer> inputs = new ArrayList<Integer>(5) { {add(10); add(10);} };
int[] results = transformService.transform(inputs);
}
public interface TransformService {
int[] transform(List<Integer> inputs);
}
#3楼
I'll throw one more in here. 我还要再扔一个。 I've noticed several uses of for loops, but you don't even need anything inside the loop. 我注意到for循环的几种用法,但是您甚至在循环内都不需要任何东西。 I mention this only because the original question was trying to find less verbose code. 我之所以提及这一点,仅是因为最初的问题是试图找到较少的冗长代码。
int[] toArray(List<Integer> list) {
int[] ret = new int[ list.size() ];
int i = 0;
for( Iterator<Integer> it = list.iterator();
it.hasNext();
ret[i++] = it.next() );
return ret;
}
If Java allowed multiple declarations in a for loop the way C++ does, we could go a step further and do for(int i = 0, Iterator it... 如果Java像C ++一样在for循环中允许多个声明,我们可以进一步做for(int i = 0,Iterator it ...
In the end though (this part is just my opinion), if you are going to have a helping function or method to do something for you, just set it up and forget about it. 最后,(这只是我的观点),如果您要使用帮助功能或方法来为您做某事,则只需进行设置,然后再进行操作即可。 It can be a one-liner or ten; 它可以是一排或十排; if you'll never look at it again you won't know the difference. 如果您再也不会看它,您将不会知道其中的区别。
#4楼
No one mentioned yet streams added in Java 8 so here it goes: 到目前为止,还没有人提到Java 8中添加了流。
int[] array = list.stream().mapToInt(i->i).toArray();
Thought process: 思考过程:
- simple
Stream#toArray
returnsObject[]
, so it is not what we want. 简单的Stream#toArray
返回Object[]
,所以这不是我们想要的。 AlsoStream#toArray(IntFunction<A[]> generator)
doesn't do what we want because generic typeA
can't represent primitiveint
另外Stream#toArray(IntFunction<A[]> generator)
不能满足我们的要求,因为通用类型A
无法表示原始int
- so it would be nice to have some stream which could handle primitive type
int
instead of wrapperInteger
, because itstoArray
method will most likely also returnint[]
array (returning something else likeObject[]
or even boxedInteger[]
would be unnatural here). 因此,最好有一些可以处理原始类型int
而不是包装器Integer
,因为它的toArray
方法很可能还会返回int[]
数组(返回诸如Object[]
或装箱的Integer[]
类的其他东西是不自然的这里)。 And fortunately Java 8 has such stream which isIntStream
幸运的是,Java 8具有这样的流,即IntStream
so now only thing we need to figure out is how to convert our
Stream<Integer>
(which will be returned fromlist.stream()
) to that shinyIntStream
. 所以现在我们唯一需要弄清楚的是如何将Stream<Integer>
(将从list.stream()
返回)转换为该闪亮的IntStream
。 HereStream#mapToInt(ToIntFunction<? super T> mapper)
method comes to a rescue. 这里Stream#mapToInt(ToIntFunction<? super T> mapper)
方法可以解决。 All we need to do is pass to it mapping fromInteger
toint
. 我们需要做的就是将它从Integer
映射到int
。 We could use something likeInteger#getValue
which returnsint
like : 我们可以使用类似Integer#getValue
东西,它返回int
像这样:mapToInt( (Integer i) -> i.intValue() )
(or if someone prefers
mapToInt(Integer::intValue)
) (或者如果有人喜欢mapToInt(Integer::intValue)
)but similar code can be generated using unboxing, since compiler knows that result of this lambda must be
int
(lambda inmapToInt
is implementation ofToIntFunction
interface which expects body forint applyAsInt(T value)
method which is expected to returnint
). 但是可以使用拆箱生成类似的代码,因为编译器知道此lambda的结果必须为int
(mapToInt
中的mapToInt
是ToIntFunction
接口的实现,ToIntFunction
接口期望int applyAsInt(T value)
主体int applyAsInt(T value)
方法,该方法应返回int
)。So we can simply write 所以我们可以简单地写
mapToInt((Integer i)->i)
Also since
Integer
type in(Integer i)
can be inferred by compiler becauseList<Integer>#stream()
returnsStream<Integer>
we can also skip it which leaves us with 同样由于编译器可以推断(Integer i)
Integer
类型,因为List<Integer>#stream()
返回Stream<Integer>
我们也可以跳过它,从而使我们mapToInt(i -> i)
#5楼
In addition to Commons Lang, you can do this with Guava 's method Ints.toArray(Collection<Integer> collection)
: 除了Ints.toArray(Collection<Integer> collection)
Lang之外,您还可以使用Guava的Ints.toArray(Collection<Integer> collection)
:
List<Integer> list = ...
int[] ints = Ints.toArray(list);
This saves you having to do the intermediate array conversion that the Commons Lang equivalent requires yourself. 这样就省去了Commons Lang等效项需要自己进行的中间数组转换的麻烦。
#6楼
try also Dollar ( check this revision ): 也可以尝试Dollars ( 检查此修订版 ):
import static com.humaorie.dollar.Dollar.*
...
List<Integer> source = ...;
int[] ints = $(source).convert().toIntArray();