I have a list of header values from an excel spreadsheet that is set up to look like a flat table. I also have a list defining the key fields of the table that the excel sheet will be inserted to. I basically want to iterate through the list of header fields, and the header exists in the list of key fields, add it to a map of some sort. What's the best way to check if the values in one list exist in another?
+1
A:
List myList = //...
List another = //...
myList.retainAll(another);
Konrad Garus
2010-07-21 13:46:31
I only need to check if the values exist. If the header is in the list of key fields, then I will proceed to add that header along with it's row value to a Map. If I'm not mistaken, the retainAll will just drop out any values not in the list of keys, giving me a clone of the keys list that I already have
john m.
2010-07-21 14:05:18
+1
A:
I believe turning your list of keys into a Set
object will give you the functionality you're looking for.
Set<String> keys = new HashSet<String>(listOKeys);
for (String header : listOHeaders) {
if (keys.contains(header)) {
// process
}
}
BlairHippo
2010-07-21 14:18:19
List has a contains method as well, although using the HashSet will most likely be faster.
Andrei Fierbinteanu
2010-07-21 14:28:31
@Andrei: Yup, O(n) for List vs O(lg n) for HashSet, unless I'm misunderstanding something. A trivial distinction for small data sets, but defaulting to efficiency is rarely a bad thing.
BlairHippo
2010-07-21 14:41:02