简体   繁体   English

有没有办法将输入矩阵转换为 ArrayLists 的 ArrayList?

[英]Is there a way to convert an input Matrix to an ArrayList of ArrayLists?

Here is an example input that I want to make an ArrayList of ArrayLists:这是一个示例输入,我想创建一个 ArrayLists 的 ArrayList:

1,0,1
1,1,1
0,0,1

I have Scanner in that holds the input and I was thinking of having a for-loop to add the numbers to the ArrayList of ArrayLists using in.nextInt() .我有Scanner in来保存输入,我正在考虑使用 for 循环将数字添加到 ArrayLists 的 ArrayList 中使用in.nextInt() But the problem is how do I find when I should move on to the next ArrayList within the big ArrayList?但问题是我如何找到我应该移动到大 ArrayList 内的下一个 ArrayList 的时间?

You could either define an arbitrary limit of numbers before moving to the next ArrayList您可以在移动到下一个 ArrayList 之前定义任意数量的限制

while (condition to keep reading)
{
 for (int i = 0; i < arbitrarylimit; i++) {
   List<Integer> list = new ArrayList<Integer>();
   // read the input 
   biglist.add(list);
 }
}

Or you could establish that if you find a new line before a number then it should be inserted into a new ArrayList.或者您可以确定,如果您在数字前找到新行,则应将其插入新的 ArrayList。

while (condition to keep reading)
{
   List<Integer> list = new ArrayList<Integer>();
   String result = scanner.nextLine();
   // split result and add it to a list
   biglist.add(list);
}

You can do it like this.你可以这样做。

  • read in each row as a single line将每一行作为单行读取
  • Each number can be separated by commas and or spaces每个数字可以用逗号和/或空格分隔
  • Use a stream and split them on the commas and spaces使用 stream 并将它们拆分为逗号和空格
    converting them to a List<Integer>将它们转换为List<Integer>
  • Then add that list to the overall list of lists.然后将该列表添加到列表的整体列表中。

String line = "";
List<List<Integer>> lists = new ArrayList<>();
// take input until a `#` is typed on a new line.
while (sc.hasNextLine()) {
    List<Integer> nums = Arrays.stream(line.split("[\\s,]+"))
            .map(Integer::parseInt)
            .collect(Collectors.toList());
    lists.add(nums);
}
lists.forEach(System.out::println);

For the following input per line对于每行以下输入

1 0,1
1,1,1
0 0 1

You get the following output你得到以下 output

[1, 0, 1]
[1, 1, 1]
[0, 0, 1]

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

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