• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Comparing List and Map

 
Jennifer Moran
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2700
IntelliJ IDE Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Mike Simmons
Ranch Hand
Posts: 3041
10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic