Iterating across a TreeMap....

  • Thread starter Christian Williamson
  • Start date
C

Christian Williamson

I'd like to iterate over a TreeMap and print out the key and value for
each entry, with each entry printout being on the same line. Anyone know
how to do that?
 
C

Christian Williamson

Logan said:
Call entrySet() and iterate over that.

Thanks, that's what I was going to do. The question then is: What do you
print for each item in the entrySet? How do you obtain the key and value
from an iterator? For example,

//add key value pairs to TreeMap
treeMap.put("2","Two");
treeMap.put("1","One");
treeMap.put("3","Three");
....
Iterator i = treeMap.entrySet().iterator();

while (i.hasNext()) {

/* What goes here? Gotta have i.next(). Then what to print key
and value? */

}
 
T

Tom Anderson

Thanks, that's what I was going to do. The question then is: What do you
print for each item in the entrySet? How do you obtain the key and value
from an iterator?

Keep reading the javadoc.

Seriously, find and read the documentation for Map.entrySet().

tom
 
C

Christian Williamson

Logan said:
Map.Entry entry = (Map.Entry) i.next();
System.out.println("key is " + entry.getKey()
+ " and value is " + entry.getValue());

The above assumes you're not using generics. I would probably do it
with generics, though:

SortedMap<String,String> map = new TreeMap<String,String>();

map.put("2", "Two");
map.put("1", "One");
map.put("3", "Three");

for (Map.Entry<String,String> entry : map.entrySet()) {
System.out.println("key is " + entry.getKey()
+ " and value is " + entry.getValue());
}

The above code is untested, but I'm fairly sure it's right.

- Logan

Excellent, thanks. Yep, it worked.

import java.util.Collection;
import java.util.TreeMap;
import java.util.Iterator;
import java.util.Set;
import java.util.Map;
import java.util.SortedMap;


public class IterateExample {

SortedMap<String,String> map = new TreeMap<String,String>();

public static void main (String [] args) {
IterateExample ie = new IterateExample();

ie.map.put("2", "Two");
ie.map.put("1", "One");
ie.map.put("3", "Three");

for (Map.Entry<String,String> entry : ie.map.entrySet()) {
System.out.println("key is " + entry.getKey()
+ " and value is " + entry.getValue());
}
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,994
Messages
2,570,223
Members
46,810
Latest member
Kassie0918

Latest Threads

Top