如何轉換清單 Java中的int []? [重複]

本文翻譯自: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 returns Object[] , so it is not what we want. 簡單的Stream#toArray返回Object[] ,所以這不是我們想要的。 Also Stream#toArray(IntFunction<A[]> generator) doesn't do what we want because generic type A can't represent primitive int 另外Stream#toArray(IntFunction<A[]> generator)不能滿足我們的要求,因爲通用類型A無法表示原始int
  • so it would be nice to have some stream which could handle primitive type int instead of wrapper Integer , because its toArray method will most likely also return int[] array (returning something else like Object[] or even boxed Integer[] would be unnatural here). 因此,最好有一些可以處理原始類型int而不是包裝器Integer ,因爲它的toArray方法很可能還會返回int[]數組(返回諸如Object[]或裝箱的Integer[]類的其他東西是不自然的這裏)。 And fortunately Java 8 has such stream which is IntStream 幸運的是,Java 8具有這樣的流,即IntStream
  • so now only thing we need to figure out is how to convert our Stream<Integer> (which will be returned from list.stream() ) to that shiny IntStream . 所以現在我們唯一需要弄清楚的是如何將Stream<Integer> (將從list.stream()返回)轉換爲該閃亮的IntStream Here Stream#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 from Integer to int . 我們需要做的就是將它從Integer映射到int We could use something like Integer#getValue which returns int 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 in mapToInt is implementation of ToIntFunction interface which expects body for int applyAsInt(T value) method which is expected to return int ). 但是可以使用拆箱生成類似的代碼,因爲編譯器知道此lambda的結果必須爲intmapToInt中的mapToIntToIntFunction接口的實現, 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 because List<Integer>#stream() returns Stream<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之外,您還可以使用GuavaInts.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();
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章