1

I have a 2D ArrayList (ArrayList within an ArrayList). For instance, I have the following values for it:

[res, 0.0]
[print, string]

Now, how can I access the index where the value "res" occurred?

3
  • your list is holding what? strings? Commented May 14, 2017 at 9:03
  • 1
    list.get(0).get(0). Commented May 14, 2017 at 9:04
  • No. I have to get the index where res occurred. Its like list.get().get().indexOf("res") Instance of res could be any value. For example, indexOf(print), etc. Commented May 14, 2017 at 9:06

2 Answers 2

4

If list is your list, you should be able to find the value "res" with:

list.get(0).get(0)

For a reference a[row][col] to an element of a 2d array, the equivalent reference to an ArrayList of ArrayLists (or really any List of Lists) will be list.get(row).get(col)

Sign up to request clarification or add additional context in comments.

2 Comments

see the comments. This is not what the OP wants
No. I have to get the index where res occurred. Its like list.get().get().indexOf("res"). Instance of res could be any value. For example, indexOf(print), etc.
2

Iterate over the list in the list:

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
        }
    }

or use a java8 stream

example:

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

2 Comments

I think this is what I'm looking for but is there any way, that I can do this without looping? I need to be time efficient in this problem. Anyway, thank you.
time efficiency is going to be hard, find in a list is a Olog(n), now imagine finding in a list of list, maybe modifying that design can help improving the efficiency....

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.