如何在Java 8中将一个二维数组或任何数组转换为List\\>?

huangapple go评论74阅读模式
英文:

How to convert an 2D array specifically or any array into List<List<Integer>> in java 8?

问题

return Arrays.stream(a)
    .map(row -> Arrays.asList(row))
    .collect(Collectors.toList());
英文:

Suppose there is an array Integer[][] a;
Then how to convert this a into List&lt;List&lt;Integer&gt;&gt; in java 8?
This is my code of leetcode Pascal's trianagle

class Solution {
	public List&lt;List&lt;Integer&gt;&gt; generate(int numRows) {

		Integer[][] a = new Integer[numRows][numRows];
		a[0][0] = 1;
		for(int i=0;i&lt;numRows;i++) {
			a[i][0] = 1;
			for(int j=0;j&lt;=i;j++) {
				if(i == j) 
					a[i][j] = 1;
					else {
						a[i][j] = a[i-1][j-1] + a[i-1][j];
					}
			}
		}
	   return ______;
	}
}

Now what should i write in return statement?

答案1

得分: 5

这将会过去。我们将使用类型为 List<List<Integer>>(所需的输出类型)的 ArrayList<>() 来存储所有行,而临时行只使用 ArrayList<>()

class Solution {
    public List<List<Integer>> generate(int numRows) {
        List<List<Integer>> rows = new ArrayList<>();
        ArrayList<Integer> row = new ArrayList<>();
        for (int i = 0; i < numRows; i++) {
            row.add(0, 1);
            for (int j = 1; j < row.size() - 1; j++)
                row.set(j, row.get(j) + row.get(j + 1));
            rows.add(new ArrayList<Integer>(row));
        }
        return rows;
    }
}

此外,还有一个关于 Pascal's Triangle 问题的数学解法(例如,在 Python 中):

import math

class Solution:
    def generate(self, size):
        if size < 0:
            return [[1]]
        rows = []
        for n in range(size):
            row = []
            for r in range(n + 1):
                row.append(math.factorial(n) // math.factorial(r) // math.factorial(n - r))
            rows.append(row)
        return rows

参考资料:

  • 有关更多详细信息,请参阅讨论板,您可以在其中找到许多解释详细的已接受解决方案,涵盖了各种编程语言,包括低复杂度算法和渐近的运行时/内存分析12
英文:

This'll pass. We'd use an ArrayList&lt;&gt;() of type List&lt;List&lt;Integer&gt; (which is the desired output) for all rows and just an ArrayList&lt;&gt;() for the temp row:

class Solution {
    public List&lt;List&lt;Integer&gt;&gt; generate(int numRows) {
        List&lt;List&lt;Integer&gt;&gt; rows = new ArrayList&lt;&gt;();
        ArrayList&lt;Integer&gt; row = new ArrayList&lt;&gt;();
        for (int i = 0; i &lt; numRows; i++) {
            row.add(0, 1);
            for (int j = 1; j &lt; row.size() - 1; j++)
                row.set(j, row.get(j) + row.get(j + 1));
            rows.add(new ArrayList&lt;Integer&gt;(row));
        }
        return rows;
    }
}

There is also a math Solution for Pascal's Triangle problem (e.g, in Python):

import math


class Solution:
    def generate(self, size):
        if size &lt; 0:
            return [[1]]
        rows = []
        for n in range(size):
            row = []
            for r in range(n + 1):
                row.append(math.factorial(n) // math.factorial(r) // math.factorial(n - r))
            rows.append(row)
        return rows


References

  • For additional details, please see the Discussion Board where you can find plenty of well-explained accepted solutions with a variety of languages including low-complexity algorithms and asymptotic runtime/memory analysis<sup>1, 2</sup>.

答案2

得分: 2

int[][] arr = { { 1, 2, 3 }, { 4, 5, 6, 7, 8, 9 }, { 10, 11, 12, 13 } };

List<List<Integer>> list1 = Arrays.stream(arr)
        .map(ar -> Arrays.stream(ar).boxed()
                .collect(Collectors.toList()))
        .collect(Collectors.toList());

List<List<Integer>> list2 = Arrays.stream(arr)
        .map(ar -> Arrays.stream(ar).boxed().collect(
                Collectors.toCollection(ArrayList::new)))
        .collect(Collectors.toCollection(ArrayList::new));

System.out.println(list1);
System.out.println(list2);

Prints

[[1, 2, 3], [4, 5, 6, 7, 8, 9], [10, 11, 12, 13]]
[[1, 2, 3], [4, 5, 6, 7, 8, 9], [10, 11, 12, 13]]
英文:

>how to convert a 2D array specifically or any array into List<List<Integer>> in java 8?

If you use lists to begin with you wouldn't need to do the conversion. But to answer your question for perhaps future reference, here is how you do it.

  • A 2D array is an array of arrays.
  • So the first stream, streams the arrays.
  • the inner stream, streams the individual arrays and collects the values into a list.
  • those lists are then once again collected into another List.
int[][] arr = { { 1, 2, 3 }, { 4, 5, 6, 7, 8, 9 },
		{ 10, 11, 12, 13 } };

The first method returns the default implementation of list.

List&lt;List&lt;Integer&gt;&gt; list1 = Arrays.stream(arr)
		.map(ar -&gt; Arrays.stream(ar).boxed()
				.collect(Collectors.toList()))
		.collect(Collectors.toList());

This method allows you to specify the collection type - in this case, an array list.

List&lt;List&lt;Integer&gt;&gt; list2 = Arrays.stream(arr)
		.map(ar -&gt; Arrays.stream(ar).boxed().collect(
				Collectors.toCollection(ArrayList::new)))
		.collect(Collectors.toCollection(ArrayList::new));

System.out.println(list1);
System.out.println(list2);

Prints

[[1, 2, 3], [4, 5, 6, 7, 8, 9], [10, 11, 12, 13]]
[[1, 2, 3], [4, 5, 6, 7, 8, 9], [10, 11, 12, 13]]


</details>



huangapple
  • 本文由 发表于 2020年8月19日 23:16:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/63490132.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定