Win a copy of Murach's Java Programming this week in the Beginning Java forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Need help for using Iterator  RSS feed

 
Ganesh Chandrasekaran
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Sheriff
Posts: 15985
86
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Ganesh Chandrasekaran
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dear Jesper Young ,



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


thanks,
Ganesh
 
Anything worth doing well is worth doing poorly first. Just look at this tiny ad:
Thoughts on deprecation in Java
https://coderanch.com/t/683016/java/Deprecation-Java
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!