简体   繁体   English

从 Java 中的二维数组创建链表

[英]Create a linked list from a 2D array in Java

If I have a 2D string array (or int array), how can take this and create a linked list out of it?The linked list can be a 2D linked list or regular linked list and it doesn't matter if the list is double, single, circular or multi-linked lists.如果我有一个 2D 字符串数组(或 int 数组),如何获取它并从中创建一个链表?链表可以是 2D 链表或常规链表,如果列表是双精度则无关紧要,单,循环或多链表。

You can either use two nested for loops or Java 8 Streams.您可以使用两个嵌套for循环或 Java 8 Streams。

For a 2-dimensional array of primitives:对于一个二维基元数组:

final int[][] arr = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9, 10 } };
final LinkedList<LinkedList<Integer>> list = Arrays.stream(arr)
        .map(x -> Arrays.stream(x).boxed().collect(Collectors.toCollection(LinkedList::new)))
        .collect(Collectors.toCollection(LinkedList::new));
System.out.println(list);

For a 2-dimensional array of objects:对于二维对象数组:

final String[][] arr2 = {
        {"a","b"},{"c"},{"d","e","f"}
};
final LinkedList<LinkedList<String>> list2 = 
        Arrays.stream(arr2).map(x -> new LinkedList<>(Arrays.asList(x)))
        .collect(Collectors.toCollection(LinkedList::new));
System.out.println(list2);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM