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

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

问题描述

我正在编写一种将列表列表中的Integer数据类型转换为 array of array的原始类型 int的方法。

I am writing a method which converts Integer data type from a List of lists, to a primitive type "int" of "array of array".

问题

Question

是否可以使用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.

我发现的东西

What I have found

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.

到目前为止,这是我的代码

This is my code so far

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;
}

预期结果

Expected results

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

错误

Errors

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

返回 java.util.List< java.lang.Integer>不能转换为int

请原谅我错误的问题/代码格式。我是stackoverflow&的新手。 Java语言的初学者,所以请纠正我。

Please forgive me for incorrect question/code formatting. I am new to stackoverflow & a beginner in Java language so please correct me.

推荐答案

要回答您的确切问题,是一个 Integer可以使用 intValue()方法将转换为 int ,也可以使用自动装箱以转换为 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;到Array&lt; Array&lt; int&gt;&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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