• 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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

best way to iterate a generic list

 
Ranch Hand
Posts: 66
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi there,

I have a generics collection list object. This is a collection of custom java object class which looks something like this
Class Custom
{
String name; int value;
}
and many other attributes in this class.

I want to lookup this generic collection. I will get the name attribute of the custom class as an input parameter. Is there a way where in can straight away look into the generic collection with the input value passed and fetch the object in question rather than sifting through all the elements of the collection.

Do post your thoughts.

Uday
 
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You will have to walk through the list until you find the object you are looking for. For example:

(assuming your class Custom has a getName() method).

But you should consider using a Map for this, and store the Custom objects in the map with their names as the keys:


 
Ranch Hand
Posts: 81
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Why not just implement the equals method for custom and use equals to find your object
 
Ranch Hand
Posts: 72
Eclipse IDE Firefox Browser Suse
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Writing an equals methods for the Custom class is as good as writing the find method as shown by Jesper. Eventually we will have to use a loop soomewhere in order to iterate through the collections. Using the hashmap is, i think, the better way to do it. .
 
Time is the best teacher, but unfortunately, it kills all of its students - Robin Williams. tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic