Reputation: 315
I want to compare a string against multiple arraylist.
Say String str;
ArrayList<String> list1;
ArrayList<String> list2;
if(list1.contains(str)
else if(list2.contains(str)
else if...
I want to do it in some another way instead of if else ladder.
Any options?
Upvotes: 0
Views: 55
Reputation: 5424
a tricky solution :
public static void main(String[] args) throws Exception {
ArrayList<String> l1 = new ArrayList<>();
ArrayList<String> l2 = new ArrayList<>();
int i = getIndex("key", l1, l2);
switch (i) {
case -1:
break;
case 0:
break;
case 1:
break;
default:
break;
}
}
public static int getIndex(String key, ArrayList<String>... arrayLists) {
for (int i = 0; i < arrayLists.length; i++) {
if (arrayLists[i].contains(key))
return i;
}
return -1;
}
Upvotes: 0
Reputation: 2732
list2 etc elements into one list using addAll() method...like..
lists.addAll(list1);
lists.addAll(list2)..
now you can iterate your list using for loop for list
for (String ele: lists) {
if (ele.equals(str) {
// do whatever you want
}
}
here you can save the iteration of list of list..
Upvotes: 0
Reputation: 3569
You could have a List of lists :
ArrayList<ArrayList<String>> lists = new ArrayList<>();
lists.add(list1);
lists.add(list2);
then you can write
for (<ArrayList<String> list : lists) {
if (list.contains(str) {
// whatever
}
}
Upvotes: 2