二维 ArrayList 中元素的索引 Java
Index of an element in a 2D ArrayList Java
我有一个 2D ArrayList(ArrayList 中的 ArrayList)。例如,我有以下值:
[res, 0.0]
[print, string]
现在,如何访问值“res”出现的索引?
如果 list
是您的列表,您应该能够通过以下方式找到值 "res":
list.get(0).get(0)
对于二维数组元素的引用 a[row][col]
,等效于对 ArrayList
的 ArrayList
的引用(或者实际上 List
的任何 List
15=]s) 将是 list.get(row).get(col)
迭代列表中的列表:
List<List<String>> dList = new ArrayList<>();
dList.add(Arrays.asList("A", "B", "C"));
dList.add(Arrays.asList("A", "B", "C"));
dList.add(Arrays.asList("A", "B", "C"));
for (List<String> list : dList) {
if (list.contains("A")) {
// todo
}
}
或使用 java8 流
示例:
List<List<String>> dList = new ArrayList<>();
dList.add(Arrays.asList("A", "B", "C"));
dList.add(Arrays.asList("f", "t", "j"));
dList.add(Arrays.asList("g", "4", "h"));
String a = dList.stream().flatMap(List::stream).filter(xx -> xx.equals("a")).findAny().orElse(null);
a = dList.stream().flatMap(List::stream).filter(xx -> xx.equalsIgnoreCase("a")).findFirst().orElse(null);
a = dList.stream().flatMap(List::stream).filter(xx -> xx.equals("h")).findFirst().orElse(null);
我有一个 2D ArrayList(ArrayList 中的 ArrayList)。例如,我有以下值:
[res, 0.0]
[print, string]
现在,如何访问值“res”出现的索引?
如果 list
是您的列表,您应该能够通过以下方式找到值 "res":
list.get(0).get(0)
对于二维数组元素的引用 a[row][col]
,等效于对 ArrayList
的 ArrayList
的引用(或者实际上 List
的任何 List
15=]s) 将是 list.get(row).get(col)
迭代列表中的列表:
List<List<String>> dList = new ArrayList<>();
dList.add(Arrays.asList("A", "B", "C"));
dList.add(Arrays.asList("A", "B", "C"));
dList.add(Arrays.asList("A", "B", "C"));
for (List<String> list : dList) {
if (list.contains("A")) {
// todo
}
}
或使用 java8 流
示例:
List<List<String>> dList = new ArrayList<>();
dList.add(Arrays.asList("A", "B", "C"));
dList.add(Arrays.asList("f", "t", "j"));
dList.add(Arrays.asList("g", "4", "h"));
String a = dList.stream().flatMap(List::stream).filter(xx -> xx.equals("a")).findAny().orElse(null);
a = dList.stream().flatMap(List::stream).filter(xx -> xx.equalsIgnoreCase("a")).findFirst().orElse(null);
a = dList.stream().flatMap(List::stream).filter(xx -> xx.equals("h")).findFirst().orElse(null);