Home Answers Viewqa Java-Beginners Define please!?!

 
 


Lara Elizabeth Wood
Define please!?!
2 Answer(s)      a year and 8 months ago
Posted in : Java Beginners

What is tree map sort?

View Answers

September 21, 2011 at 5:48 PM


The TreeMap class implements the Map interface by using a tree. A TreeMap provides an efficient means of storing key/value pairs in sorted order, and allows rapid retrieval. You should note that, unlike a hash map, a tree map guarantees that its elements will be sorted in ascending key order.

Here is an example that will display the treemap elements in a sorted way:

import java.util.*;

public class TreeMapExample {
  public static void main(String args[]) {
    String days[] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
    int no[] = { 1, 2, 3, 4, 5, 6, 7 };
    TreeMap<String,Integer> map = new TreeMap<String,Integer>();
    for (int i = 0, n = days.length; i < n; i++) {
      map.put(days[i], new Integer(no[i]));
    }
    Iterator it = map.keySet().iterator();
    Object obj;
    while (it.hasNext()) {
      obj = it.next();
      System.out.println(obj + ": " + map.get(obj));
    }
  }
}

September 21, 2011 at 5:49 PM


The TreeMap class implements the Map interface by using a tree. A TreeMap provides an efficient means of storing key/value pairs in sorted order, and allows rapid retrieval. You should note that, unlike a hash map, a tree map guarantees that its elements will be sorted in ascending key order.

Here is an example that will display the treemap elements in a sorted way:

import java.util.*;

public class TreeMapExample {
  public static void main(String args[]) {
    String days[] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
    int no[] = { 1, 2, 3, 4, 5, 6, 7 };
    TreeMap<String,Integer> map = new TreeMap<String,Integer>();
    for (int i = 0, n = days.length; i < n; i++) {
      map.put(days[i], new Integer(no[i]));
    }
    Iterator it = map.keySet().iterator();
    Object obj;
    while (it.hasNext()) {
      obj = it.next();
      System.out.println(obj + ": " + map.get(obj));
    }
  }
}









Related Pages:

Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.