0

Thanks for taking the time to look at my question.

I am using a Tree map to add data into my system

private static Map employeeMap = new TreeMap();

I have then created employee objects like so

theEmployee = new Employee(randomIDno,fName, sName, gender, dPayLevel);

I then add it to the tree map like this

employeeMap.put(randomIDno,theEmployee);

I would just like to know how to iterate through all the Employee objects contained in this treeMap and print it out to the screen?

Binyomin
  • 367
  • 2
  • 7
  • 20

3 Answers3

0

In case you need to sort the elements in a different order than the default one. Override the equals() method for the object or provide a Comparator in the constructor

Gavin
  • 91
  • 1
  • 9
0

If you don't care about order or the TreeMap is maintaining order for you, it's quite simple to use the values() method:

for(Employee employee : employeeMap.values()) {
  System.out.println(employee);
}
  • Thanks!! Yes the treeMap should be keeping order for me anyway. – Binyomin Oct 19 '11 at 02:36
  • and If I wanted to change an ovjects name or last name would I go for(Employee employee : employeeMap.values()) { employee.setname(value) – Binyomin Oct 19 '11 at 02:43
  • Yes, if your `Employee` object is mutable that is what you would use. –  Oct 19 '11 at 03:10
0

You could use the Iterator in java

Set s = employeeMap.entrySet();
Iterator i = s.iterator();

while (i.hasNext())
{
    // display each item.
}
Paul Trone
  • 11
  • 2