aspose file tools*
The moose likes Beginning Java and the fly likes Need help  for  using Iterator Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Need help  for  using Iterator" Watch "Need help  for  using Iterator" New topic
Author

Need help for using Iterator

Ganesh Chandrasekaran
Greenhorn

Joined: Nov 14, 2000
Posts: 22
Hi,

1. I use the following code for HashMap, is it fine?

----------

HashMap hm = new HashMap();

hm.put("1","aaa");
hm.put("2","bbb");
hm.put("3","ccc");
hm.put("4","ddd");
hm.put("5","eee");
hm.put("6","fff");
hm.put("7","ggg");
hm.put("8","hhh");
hm.put("9","iii");
hm.put("10","jjj");
hm.put("11","kkk");
hm.put("12","lll");
hm.put("13","mmm");
hm.put("14","nnn");
hm.put("15","ooo");


Set st = hm.entrySet();

Iterator myIt = st.iterator();


while(myIt.hasNext())
{
Map.Entry mapEntry = (Map.Entry)myIt.next();

System.out.println("==="+mapEntry.getKey()+" --- "+mapEntry.getValue());

}


--------

the output i get is

===3 --- ccc
===7 --- ggg
===2 --- bbb
===14 --- nnn
===1 --- aaa
===6 --- fff
===10 --- jjj
===5 --- eee
===13 --- mmm
===15 --- ooo
===9 --- iii
===11 --- kkk
===4 --- ddd
===8 --- hhh
===12 --- lll

which is in different order., but i want it in the same order
as i have input.

Please do help me in solving this problem.

thanking in advance
Ganesh
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 13884
    
  10

1. I use the following code for HashMap, is it fine?

Yes, it's fine.

About the order: Maps do not generally store elements in a predictable order, so it's not strange that the elements are listed in a different order than how you put them in the map.

Use LinkedHashMap instead of HashMap if you want the elements to be listed in the order that you put them in the map.


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
Ganesh Chandrasekaran
Greenhorn

Joined: Nov 14, 2000
Posts: 22
Dear Jesper Young ,



Thank you very much for your suggestion, It is working as i wanted.


thanks,
Ganesh
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Need help for using Iterator
 
Similar Threads
Example Code for testing DB access and row locking
My Test Code for DB Locking, etc.
following::* doubt
How to split a string by the whitespace but ignoring '\n'?
Xpath Requirement help!!