jQuery in Action, 2nd edition*
The moose likes Java in General and the fly likes Comparing List and Map Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Java in General
Bookmark "Comparing List and Map " Watch "Comparing List and Map " New topic
Author

Comparing List and Map

Jennifer Moran
Ranch Hand

Joined: Oct 21, 2002
Posts: 60
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

Thanks,

Jennifer
Wouter Oet
Saloon Keeper

Joined: Oct 25, 2008
Posts: 2700

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.
Mike Simmons
Ranch Hand

Joined: Mar 05, 2008
Posts: 3016
    
  10
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.
 
GeeCON Prague 2014
 
subject: Comparing List and Map