I have a List defined as <Foo> - Foo has a field called ID
I have a Map defined as <String, String> - this is created by a properties file early on
I need to compare the values in the Map to see if they exist as an ID in Foo.
So what is the best way to do this? Do I loop through each and compare? That seems not such a good idea. I was looking at contains but I need an object of Foo and I only have a Map<String, String>. I know I am missing something I am just not sure what
You get get a Collection with the values and use the retainAll method with your List. Then you'll end up with the values that are in the Map and List.
"Any fool can write code that a computer can understand. Good programmers write code that humans can understand." --- Martin Fowler
Please correct my English.
Joined: Mar 05, 2008
If I understand both of you correctly, I don't think Wouter's suggestion will work. The values in the map are all Strings, and the things in the list are all Foos. Somewhere some code needs to call foo.getID() to convert the Foos to Strings. (I assume the ID is a String, otherwise we may need another step as well) Since we don't have closures, it probably needs to be done in a loop.
Jennifer Moran wrote:Do I loop through each and compare? That seems not such a good idea.
I think that is what you need to do. Why doesn't it sound like a good idea? Other languages have mechanisms for handling this a little more elegantly, but in Java looping through is probably the way to go. There's a way to do this with the Google Collections library, but until JDK 8 comes out it will probably look at least as complex as the looping code would.