In this example we will see how and when to use java.util.TreeMap.
A TreeMap
is a Map implementation which provides total ordering on its elements. The elements are ordered using their natural ordering, or by a Comparator
typically provided at sorted map creation time.
A TreeMap
is a Red-Black tree based NavigableMap
implementation which insures log(n) time cost for the basic operations (add, remove and contains).
A TreeMap
is typically used when, in a map, we want to keep the elements sorted all times. The elements are sorted by the keys in a map. The keys could also be custom objects defined with comparable
/comparator
to decide the attribute responsible for sorting.
Important thing to note is that the ordering maintained by a treeMap
must be consistent with equals if this sorted map is to correctly implement the Map
interface.
Let’s see how we can use TreeMap
in different ways :
理解:(1)TreeMap是一个Map的实现,它能够对自己的元素进行排序 (2)TreeMap的基础是一个红黑树,基本的增删操作的复杂度为log(n) (3)当我们需要map中的元素保持有序的时候,就可以用TreeMap。元素是根据键值进行排序的。键可以是用户定义的对象,可以通过compare/comparator来指定对象中的某个属性来进行排序
A TreeMap
guarantees that the elements inserted remains sorted on the order of keys, let’s see the example :
package com.jcg.example; import java.util.Map; import java.util.TreeMap; public class JavaTreeMapExample { public static void main(String[] args) { //Natural ordering of key Integer Map integerMap = new TreeMap(); integerMap.put(1, "ABC"); integerMap.put(2, "PQR"); integerMap.put(3, "XXX"); integerMap.put(4, "YYY"); System.out.println(integerMap.toString()); } }
{1=ABC, 2=PQR, 3=XXX, 4=YYY}
理解:当Key为Integer的时候,根据Integer的大小来进行排序
Now let’s see how we can use custom classes as keys using Comparable
. For this example we will use a User
class and implement Comparable
.
package com.jcg.example; public class User implements Comparable { private String firstName; private String lastName; private int salary; public User(String firstName, String lastName, int salary) { super(); this.firstName = firstName; this.lastName = lastName; this.salary = salary; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public int getSalary() { return salary; } public void setSalary(int salary) { this.salary = salary; } @Override public String toString() { return firstName + " " + lastName + " " + salary; } @Override public int compareTo(User o) { return this.firstName.compareTo(o.firstName); } }
Now let’s see how to use TreeMap
to get the inserted elements sorted on the basis of firstName.
package com.jcg.example; import java.util.Map; import java.util.Set; import java.util.TreeMap; public class JavaTreeMapExample { public static void main(String[] args) { //Natural ordering of User Map userMap = new TreeMap(); populateUserMap(userMap); System.out.println(userMap.toString()); diplayMap(userMap); } private static void diplayMap(Map userMap) { Set keySet = userMap.keySet(); for (User user : keySet) { System.out.println(user.toString()); } } private static void populateUserMap(Map userMap) { userMap.put(new User("Ani","Bha",12), "My Name1"); userMap.put(new User("Cal","YYY",15), "My Name2"); userMap.put(new User("XYZ","WER",22), "My Name3"); userMap.put(new User("SSS","TER",1), "My Name4"); } }
OUTPUT :
{Ani Bha 12=My Name1, Cal YYY 15=My Name2, SSS TER 1=My Name4, XYZ WER 22=My Name3} Ani Bha 12 Cal YYY 15 SSS TER 1 XYZ WER 22
理解:根据User的firstname进行排序
Let’s say we want to sort the elements on the basis of users salaries, for this we need to implement a Comparator
:
package com.jcg.example; import java.util.Comparator; public class UserSalaryComparator implements Comparator { // This compares employees based on salaries @Override public int compare(User o1, User o2) { if (o1.getSalary() >= o2.getSalary()) { return 1; } else { return -1; } } }
Now, let’s see how to use TreeMap
to get the inserted elements sorted on the basis of salary.
package com.jcg.example; import java.util.Map; import java.util.Set; import java.util.TreeMap; public class JavaTreeMapExample { public static void main(String[] args) { //Ordering based on Comparator on salary Map userSalaryMap = new TreeMap(new UserSalaryComparator()); populateUserMap(userSalaryMap); System.out.println(" *** BASED ON SALARY ***"); diplayMap(userSalaryMap); } private static void diplayMap(Map userMap) { Set keySet = userMap.keySet(); for (User user : keySet) { System.out.println(user.toString()); } } private static void populateUserMap(Map userMap) { userMap.put(new User("Ani","Bha",12), "My Name1"); userMap.put(new User("Cal","YYY",15), "My Name2"); userMap.put(new User("XYZ","WER",22), "My Name3"); userMap.put(new User("SSS","TER",1), "My Name4"); } }
OUTPUT :
*** BASED ON SALARY *** SSS TER 1 Ani Bha 12 Cal YYY 15 XYZ WER 22
So, here we see the output is sorted in increasing order of salaries of users.
理解:用Compator类根据员工的薪水高低来进行排序