The TreeMap is used to store <key, value> pairs. It is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used.
A few important facts about TreeMap are as follows:
- It is not synchronized.
- It does not allow null keys, but values can be null.
Hierarchy of TreeMap class
It inherits methods from AbstractMap and implements Serializable, Clonable, and NavigatableMap interfaces.
Source code of Item.java
package com.t4b.test;
public class Item {
String name;
int id;
double price;
public Item(String name, int id, double price) {
super();
this.name = name;
this.id = id;
this.price = price;
}
@Override
public String toString() {
return "Item [name=" + name + ", id=" + id + ", price=" + price + "]";
}
}
Source code of TestMain.java
package com.t4b.test;
import java.util.TreeMap;
import java.util.Map;
public class TestMain {
public static void main(String[] args) {
TreeMap<Integer, Item> map = new TreeMap<Integer, Item>();
map.put(1, new Item("Apple", 1, 150.0));
map.put(2, new Item("Grape", 2, 250.0));
map.put(3, new Item("Mango", 3, 10));
map.put(2, new Item("Pine Apple", 4, 100));
for (Map.Entry item : map.entrySet()) {
System.out.println(item.getKey() + " : " + item.getValue());
}
}
}
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.