Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Java iterator question

Status
Not open for further replies.

sachint78

Programmer
May 21, 2009
1
US
Iam a newbie, I have a question.

I have a map.I have to loop through the map and build the iterator

example

public Iterable<Test> getTests(Map<String, Test> testMap,
Set<String> strings)

{
loop tru the set of strings and build iterator.
for(final String test1 : strings)
{

Test test = testMap.get(test1);

//build a iterator. not a list.
}

return iterator
}

How can I do this.

Thank You in advance.

-Sachin
 
I am not sure why would you not want to form a list! If you pass back a list, you would automatically get an iterator for the list.
 
Hi there.

I'm not sure if this does the trick, but try testMap.entrySet().iterator() and see if this helps.
 
Some musings :-

You do not need to re-invent the wheel to iterate through any collection. Iteration over items in a collection is already done for you. You can either use the iterator() method to access an iterator, or use the new for( item : collection ) construct to iterator over the collection directly.

The only time I would ever feel the need to build my own iterator implementation is if I had some set of data items which didn't fit any of the provided Collection framework containers like Lists, Sets or whatever. I'd have to make my own collection class and then provide an iterator too.

If I wanted to iterate over a collection in some non-standard ordering fashion, then I'd make a Comparator to sort the collection first then use the normal iterator() method. If this was too time-intensive in a time-sensitive application, though, I might then create a custom iterator to enumerate the items without having to sort first.

Tim
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top