• Post Reply Bookmark Topic Watch Topic
  • New Topic

best way to iterate a generic list  RSS feed

 
Udayan Kumar
Ranch Hand
Posts: 66
  • Mark post as helpful
  • send pies
  • 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
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • 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:


 
Sunil Kumar
Ranch Hand
Posts: 81
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why not just implement the equals method for custom and use equals to find your object
 
Janardan Kelkar
Ranch Hand
Posts: 72
Eclipse IDE Firefox Browser Suse
  • Mark post as helpful
  • send pies
  • 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. .
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!