• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Junilu Lacar
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • Jeanne Boyarsky
  • Rob Spoor
  • Bear Bibeault
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Piet Souris
  • Carey Brown
  • Stephan van Hulst
Bartenders:
  • Frits Walraven
  • fred rosenberger
  • salvin francis

Comparing List and Map

 
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Bartender
Posts: 2700
IntelliJ IDE Opera
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Master Rancher
Posts: 3930
51
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Squanch that. And squanch this tiny ad:
Thread Boost feature
https://coderanch.com/t/674455/Thread-Boost-feature
reply
    Bookmark Topic Watch Topic
  • New Topic