public
TreeMap(Comparator<? super K> comparator)
Constructs
a new, empty tree map, ordered according to the given comparator.
class Employee1{ Integer number; String name; Employee1(int number, String name){ this.number = number; this.name = name; } public String toString(){ return number + " " + name; } }
import java.util.Comparator; class EmployeeIdComparator implements Comparator<Employee1>{ public int compare(Employee1 e1, Employee1 e2){ return e1.number.compareTo(e2.number); } public String toString(){ return "EmployeeIdComparator"; } }
import java.util.*; class TreeMapConstructor2{ public static void main(String args[]){ TreeMap<Employee1, Integer> myMap; myMap = new TreeMap<> (new EmployeeIdComparator()); /* Insert data to myMap */ myMap.put(new Employee1(4, "Krishna"), 15000); myMap.put(new Employee1(2, "Anand"), 95000); myMap.put(new Employee1(3, "Kishore"), 50000); myMap.put(new Employee1(1, "Raju"), 70000); System.out.println("Elements in myMap are"); System.out.println(myMap); } }
Output
Elements in myMap are {1 Raju=70000, 2 Anand=95000, 3 Kishore=50000, 4 Krishna=15000}
No comments:
Post a Comment