我正在从文本文件中读取内容,并将其解析为单独的ArrayList。
例如,文本文件显示为:
Fruit1
Fruit2
Fruit3
Vegetable1
Vegetable2
Vegetable3
Vegetable4
目前,我有一个代码将每个组分成自己的数组
fruits = [Fruit1, Fruit2, Fruit3]
vegetables = [Vegetable1, Vegetable2, Vegetable3, Vegetable4]
如何使用这两个现有ArrayList中的 n 行和 m 列创建矩阵?
我的目标输出是生成一个3x4矩阵,如下所示
| Fruit1, Fruit2, Fruit3
Vegetable1|
Vegetable2|
Vegetable3|
Vegetable4|
|
我已经看到了一些示例,这些示例演示了初始化矩阵,但是,如果我将文本文件更新为可以说是3x20矩阵或5x20矩阵,我希望代码运行相同的位置,这正是我在努力的地方。
这是我为矩阵编写的代码:
List<List<String>> matrix = new ArrayList<List<String>>();
matrix.add(fruits);
matrix.add(vegetables);
System.out.println(matrix);
但是,这是输出,仅将它们组合在一起
[Fruit1, Fruit2, Fruit3, Vegetable1, Vegetable2, Vegetable3, Vegetable4]
如何创建矩阵,使一个ArrayList成为行,另一个ArrayList成为列?
答案 0 :(得分:0)
假设您需要以下矩阵:
node.max_local_storage_nodes: 2
您可以使用以下代码使用Vegetable1 | Fruit1, Fruit2, Fruit3
Vegetable2 | Fruit1, Fruit2, Fruit3
Vegetable3 | Fruit1, Fruit2, Fruit3
Vegetable4 | Fruit1, Fruit2, Fruit3
进行所有比较:
ArrayList
仅此而已,就不需要嵌套列表。如果您真的想要一个矩阵,则需要对代码进行一些修改:
List<String> vegetables = new ArrayList<>(); // Fill the lists somehow
List<String> fruits = new ArrayList<>();
for(String vegetable : vegetables) {
for(String fruit : fruits) {
System.out.printf("Compare %s to %s%n", vegetable, fruit);
}
}
这将创建包含项List<String> vegetables = new ArrayList<>(); // Fill the lists somehow
List<String> fruits = new ArrayList<>();
List<List<String>> matrix = new ArrayList<>();
for(String vegetable : vegetables) {
List<String> row = new ArrayList<String>();
row.add(vegetable);
for(String fruit : fruits) {
row.add(fruit);
}
matrix.add(row);
}
的行,其中N是蔬菜行的编号。