如何转换清单 <Integer> 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();
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值