john m.
john m.

Reputation: 189

Check to see if element of one list exists in another list

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?

Upvotes: 2

Views: 4916

Answers (2)

BlairHippo
BlairHippo

Reputation: 9658

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
    }
}

Upvotes: 2

Konrad Garus
Konrad Garus

Reputation: 54035

List myList = //...
List another = //...
myList.retainAll(another);

Upvotes: 1

Related Questions