本文翻譯自: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();