Reputation: 1107
I have an arraylist Arraylist<String[]>
and I am trying to find a quick way of looking for a specific value on a specific index of the String[]
. My ArrayList
is always going to contain String[]
of length 2. And what I want to do is look through the ArrayList
for any String[]
that has a specific value i.e. str[1]="value"
. I know that I can iterate through the ArrayList
taking every single element (String[]
) and then looking for the value using str[1].equals("value")
but I was wondering if there is a quicker way of doing it by maybe using contains()
of the ArrayList
or something.
thanks
PS: I don't know the value of the first element of my array (str[0]
) so I cannot construct a new String[]
and check if the ArrayList
contains that
Upvotes: 1
Views: 2444
Reputation: 4945
How about using a LinkedHashMap<String, String[]>
instead of the ArrayList
? The key would be the String[1]
value. Linked
because that gives you predictable iteration order.
Or you could create a Map<String, Integer>
where the key is the String[1]
value and the value is the index of your String[]
in the ArrayList
.
ArrayList<String[]> al = new ArrayList<>();
Map<String, Integer> alIndexMap = new HashMap<>();
// ...
Integer nextIndex = al.size();
al.add(someStringArray);
alIndexMap.put(someStringArray[1], nextIndex);
If you keep al
and alIndexMap
in sync all the time, you'll always know where in al
is the array that you're looking for.
Google's Guava has some classes that implement their BiMap
interface. It's like a Map
, but it works both ways, i.e. you can use the value
as a key
if you want.
Upvotes: 1
Reputation: 2962
If you look into ArrrayList#contains - you will see, that this method also iterates through all elements.
You could use a parallelStream - so that the ArrayList can be searched by more threads.
List<String[]> listToSearchIn = new ArrayList<String[]>();
List<String[]> matches = listToSearchIn.parallelStream()
.filter((element) -> element[1].equals("value"))
.collect(Collectors.toList());
Upvotes: 1
Reputation: 383
Unless your ArrayList is sorted then O(n) efficiency is the best you can do. Unless by "quick way" you mean a method which does the iteration for you. Even in this scenario the answer is no since you're wanting to check data inside the String[] objects themselves.
Upvotes: 0