• Post Reply Bookmark Topic Watch Topic
  • New Topic

Iterating over a LinkedHashMap  RSS feed

 
Dwayne Barsotta
Ranch Hand
Posts: 86
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a LinkedHashMap in my program.  I want to iterate over every key/value pair and print the key and value to the screen.  Can someone help with this?  Most I can find is printing one or the other, but not both.

Thanks
 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Have you looked at the entrySet() method? It contains a Set of key/value pairs, which you can iterate through.

Henry
 
Dwayne Barsotta
Ranch Hand
Posts: 86
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you, Yes I just found that a second ago!  I figured another way but it is a little slower.  Now I am working on a different problem.  
 
Campbell Ritchie
Marshal
Posts: 56518
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Go through the methods for LinkedHashMap, and you will find a method to give you a Stream<K> representing the keys in order. I think all Maps have such a method but in different sorts of Map you get the keys in a different order. Use that Stream or similar. If you iterate all the entries, you can get the K or the V from the entry with the Stream#map method. Look through the Java™ Tutorials and you will find an example of a Stream in there. Maybe in the section about Lists.
 
Campbell Ritchie
Marshal
Posts: 56518
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think I was mistaken in my last post; you will have to use the entrySet method and that Set shou‍ld have a stream() method.
 
Dave Tolls
Ranch Foreman
Posts: 3056
37
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Map has a forEach method for iterating over each entry and doing something with them.

I know this as I only just used it...
 
Dwayne Barsotta
Ranch Hand
Posts: 86
1
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks guys.  Yea I kind of have yup on that last night for now.   I didn't think of the stream idea, I'll look into that.  As for the forEach() method, I thought there was a method like that for simple use of the elements but I couldn't find it last night going through the java documentation for maps.  It was getting late and I tired, I don't like putting going to bed not having solveda problem. I end up laying there hours thinking about it.

Thanks guys
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!