0

I have 2D ArrayList and I want to find the index of a String located in the 1st Column.

arraylist.get(0).indexOf("My String") returns the index of a string located at first row. But I want something like this

arraylist.indexOf("MyString").get(0)
ernest_k
  • 44,416
  • 5
  • 53
  • 99
saffi ullah
  • 47
  • 1
  • 6
  • 1
    Afaik there is no build-in function to do that. You will have to iterate over those ArrayLists to find it yourself – Amongalen Feb 20 '20 at 08:43
  • So you want to find index of the first row, which has a column with the value `MyString`? – Jan Held Feb 20 '20 at 08:59

2 Answers2

0

If I understood you correct, you want to find the row, in which a column has a given value.

One thing you could do is to transpose the complete table, meaning rows become columns and columns become rows. Then you could access everything with standard Java functionality. But that's probably overkill and would assume that each row has the same amount of columns.

Instead I would recommend to just search for it like so:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class JustADemo {

    public static void main(String[] args) {
        final List<List<String>> table = new ArrayList<>();
        table.add(Arrays.asList("R1 C1", "R1 C2", "R1 C3"));
        table.add(Arrays.asList("R2 C1", "R2 C2", "R2 C3"));
        table.add(Arrays.asList("R3 C1", "R3 C2", "R3 C3"));
        int i = findRowWhereColumnEquals(table, "R3 C2");
        if (i != -1) {
            System.out.println("R3 C2 can be found in row " + i + ".");
        } else {
            System.out.println("R3 C2 cound not be found.");
        }
    }

    private static int findRowWhereColumnEquals(List<List<String>> table, String value) {
        int i = 0;
        for (List<String> row : table) {
            if (row.contains(value)) {
                return i;
            }
            i++;
        }
        return -1;
    }
}
Jan Held
  • 634
  • 4
  • 14
0

I have one question for you. How many times do you intend to perform that search (of that String or another one)?

If it is only once you will have to iterate over the ArrayLists until you find the right one.

BUT if you intend to perform several searches in the same column of the bi-dimensional array, I would advice you to make a transposed-copy of that structure and keep it in a variable in memory. You need to be aware that if the rows of the bi-dimensional array have different sizes, then you cannot make this operation.

By this way you will avoid the need of looping through multiple arrays and save some computing time in next searches. Then the look up would be close to what you want:

Integer index = arraylist_transposed[0].indexOf("MyString");
List<String> result = arraylist.get(index);

You can take a look to this question for doing the transpose of your bidimensional array: Transpose a 2d Array with varying dimensions in Java

Reubems
  • 51
  • 7