【问题标题】:Index of an element in a 2D ArrayList Java2D ArrayList Java 中元素的索引
【发布时间】:2017-05-14 09:00:59
【问题描述】:

我有一个 2D ArrayList(ArrayList 中的 ArrayList)。例如,我有以下值:

[res, 0.0]
[print, string]

现在,我如何访问出现“res”值的索引?

【问题讨论】:

  • 你的名单是什么?字符串?
  • list.get(0).get(0).
  • 没有。我必须得到 res 发生的索引。它类似于 list.get().get().indexOf("res") res 的实例可以是任何值。比如indexOf(print)等

标签: java arrays list arraylist 2d


【解决方案1】:

如果list 是您的列表,您应该能够通过以下方式找到值“res”:

list.get(0).get(0)

对于对二维数组元素的引用 a[row][col],对 ArrayListArrayLists(或实际上任何 ListLists)的等效引用将是 list.get(row).get(col)

【讨论】:

  • 查看 cmets。这不是 OP 想要的
  • 没有。我必须得到 res 发生的索引。它就像 list.get().get().indexOf("res")。 res 的实例可以是任何值。比如indexOf(print)等
【解决方案2】:

遍历列表中的列表:

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);

【讨论】:

  • 我认为这就是我正在寻找的东西,但是有什么方法可以让我在不循环的情况下做到这一点?我需要在这个问题上保持时间效率。无论如何,谢谢。
  • 时间效率会很难,在列表中查找是一个Olog(n),现在想象在列表列表中查找,也许修改该设计可以帮助提高效率....
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-30
  • 1970-01-01
相关资源
最近更新 更多