转换List< List< Integer>>到int [] [] [英] Converting List<List<Integer>> to int[][]

查看:89
本文介绍了转换List< List< Integer>>到int [] []的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一种将 Integer 数据类型从 List s的 List 转换为原始数组数组的方法,该数组的类型为 int [] [] .

I am writing a method which converts Integer data type from a List of Lists, to a primitive array of arrays, type int[][].

问题

是否可以使用Java API将 Integer 转换为 int ?

Is there any way to convert Integer to int using Java API?

仅供参考, int []设置将用于其他目的,请忽略.

For your information, int[] set will be used for other purposes so please ignore.

我发现的东西

Apache Commons API"toPrimitive"方法将Integer转换为int类型.但是,我只是在寻找使用本机Java API的解决方案.

Apache Commons API "toPrimitive" method converts Integer to int type. However, I'm only looking for solutions using native java API.

这是我到目前为止的代码

class Test {
    int[][] convert(int[] set) {
        List<List<Integer>> ll = new ArrayList<List<Integer>>();
        ll.add(new ArrayList<Integer>());
        ll.add(new ArrayList<Integer>());
        ll.add(new ArrayList<Integer>());
        ll.get(0).add(1);
        ll.get(0).add(2);
        ll.get(1).add(2);
        ll.get(2).add(3);

        System.out.println(ll + " " + ll.size());

        int[][] tempArray = new int[0][0];
        for (int i = 0; i < ll.size(); i++) {
            for (int j = 0; j < ll.get(i).size(); j++) {
                tempArray[i][j] = ll.get(j);
            }
        }
        return tempArray;
    }
}

预期结果

List entry: [[1,2],[2],[3]]
return: {{1,2},{2},{3}}

错误

tempArray [i] [j] = ll.get(j);

返回 java.util.List< java.lang.Integer>无法转换为int .

推荐答案

要回答您的确切问题,可以使用 Integer 转换为 int > intValue()方法,或者您可以使用自动装箱将其转换为 int .

To answer your exact question, yes an Integer can be converted to an int using the intValue() method, or you can use auto-boxing to convert to an int.

因此,循环的最内层部分可能是以下之一:

So the innermost part of your loop could be either of these:

tempArray[i][j] = ll.get(i).get(j).intValue();
tempArray[i][j] = ll.get(i).get(j);


但是,我们也可以采取不同的策略.


However, we can also take a different strategy.

作为对类似问题的此答案的修改,在Java 8中,您可以使用Streams映射到整数大批.这种结构只需要一个额外的映射层即可.

As a modification of this answer to a similar question, in Java 8 you can use Streams to map to an integer array. This structure just requires an extra layer of mapping.

List<List<Integer>> list = new ArrayList<>();

int[][] arr = list.stream()
    .map(l -> l.stream().mapToInt(Integer::intValue).toArray())
    .toArray(int[][]::new);

Ideone演示

这篇关于转换List&lt; List&lt; Integer&gt;&gt;到int [] []的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆