Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Home Answers Viewqa Java-Beginners Define please!?!

Have Programming Question? Ask it here!
 
 
 


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


What is tree map sort?


Advertisement
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 Tutorials/Questions & Answers:
 

 

 

DMCA.com