CodeMonkey
CodeMonkey

Reputation: 2295

Look for an element in a 2d Array using contains

I have a 2D array and want to use contains method to check if myChar is part of myArray[i][0]

public static final String[][] myArray = {
        {"NM1", "DESC1"},
        {"NM2", "DESC2"},
        {"NM3", "DESC3"},
        {"NM4", "DESC4"},
        {"NM5", "DESC5"}
    }

Arrays.asList(myArray).contains(mychar);

However this is failing for me. When i make it as 1D array like:

public static final String[][] myArrayNm = {
    "NM1",
    "NM2",
    "NM3",
    "NM4",
    "NM5"
}

Arrays.asList(myArrayNm).contains(mychar);

is working for me. Is there a way i can do the value check using 2D array (loop will be the last option)

Upvotes: 0

Views: 2147

Answers (3)

amudhan3093
amudhan3093

Reputation: 750

Try this

List<String> list = new ArrayList<String>();
    for (String[] array : myArray) {
        list.addAll(Arrays.asList(array));
    }
System.out.println(list.contains(mychar));

Upvotes: 0

devops
devops

Reputation: 9179

Try this one:

public static final String[][] myArray = {
        {"NM1", "DESC1"},
        {"NM2", "DESC2"},
        {"NM3", "DESC3"},
        {"NM4", "DESC4"},
        {"NM5", "DESC5"}
    }

List<String[]> list = Arrays.asList(myArray);
for(String[] arr: list){
    System.out.println(Arrays.asList(arr).contains("myString"));
}

Not realy performant, but it works :)

Upvotes: 2

codebox
codebox

Reputation: 20254

The problem is that when you turn your 2D array into a list you are creating a list where the elements are arrays, not strings.

Upvotes: 0

Related Questions