• Post Reply Bookmark Topic Watch Topic
  • New Topic

Retrieving members of a collection  RSS feed

 
Shweta Grewal
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi all,
I want to retrieve all the members of collection one by one.How can I do this?
 
Maneesh Godbole
Bartender
Posts: 11445
18
Android Eclipse IDE Google Web Toolkit Java Mac Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Use an Iterator
 
Anayonkar Shivalkar
Bartender
Posts: 1558
5
Eclipse IDE Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Shweta Grewal wrote:hi all,
I want to retrieve all the members of collection one by one.How can I do this?

Well, to me, it seems to be quite a generic question. What exactly do you mean by collection? There are different methods to retrieve objects from collection (e.g. List, Map, Set etc.)
 
Mike Simmons
Ranch Hand
Posts: 3090
14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
All Collections (including Lists, Sets, and Queues) have Iterators. Use those.

All Maps have three methods that return different Collections, which of course have Iterators. Those methods are keySet(), values(), and entrySet(). Use those depending on whether you want to see (a) keys only, (b) values only, or (c) both.
 
Greg Charles
Sheriff
Posts: 3015
12
Firefox Browser IntelliJ IDE Java Mac Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The new for syntax (Java 1.5) allows you to avoid explicit iterators in many cases.



Becomes



Easier to write, easier to read. Everyone's happy! Also, it works with arrays as well. See http://docs.oracle.com/javase/1.5.0/docs/guide/language/foreach.html
 
Mike Simmons
Ranch Hand
Posts: 3090
14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, this is the correct way to use an Iterator.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!