tags:

views:

59

answers:

2

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
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.
+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
List has a contains method as well, although using the HashSet will most likely be faster.
Andrei Fierbinteanu
@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