Baker1562 Baker1562 - 2 months ago 12
Java Question

Find value in String[] inside List and erase the String[]

List<String[]> data = new ArrayList<>();
data.add(new String[]{"bdc", "house2", "car2"});
data.add(new String[]{"abc", "house", "car"});


I have to questions about it:


  1. How to find for example, what is the value or second argument if I have
    abc
    , I want to find the value
    house
    ? (I don't know what is my second argument of course only the first);

  2. How to erase all the
    String[]
    if I have again for example
    abc
    ?


Answer
  1. To access to a given index of an array, use the square brackets array[index] knowing that index goes from 0 to array.length - 1.
  2. To remove an element of a Collection while iterating over it, you can use iterator.remove().

So your code could look like:

// Flag used to know if it has already been found
boolean found = false;
for (Iterator<String[]> it = data.iterator(); it.hasNext();) {
    String[] values = it.next();
    // Check if the first element of the array is "abc"
    if (values.length > 1 && "abc".equals(values[0])) {
        if (found) {
            // Already found so we remove it
            it.remove();
            continue;
        }
        // Not found yet so we simply print it
        System.out.println(values[1]);
        found = true;
    }
}

Output:

house