博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
TreeMap的学习
阅读量:4455 次
发布时间:2019-06-07

本文共 5671 字,大约阅读时间需要 18 分钟。

In this example we will see how and when to use  A TreeMap is a Map implementation which provides total ordering on its elements. The elements are ordered using their natural ordering, or by a  typically provided at sorted map creation time.

TreeMap is a Red-Black tree based NavigableMap implementation which insures log(n) time cost for the basic operations (add, remove and contains).

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来指定对象中的某个属性来进行排序 

1. Keys as Integers

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的大小来进行排序

 

2. Keys as Custom Classes using Comparable

Now let’s see how we can use custom classes as keys using  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 12Cal YYY 15SSS TER 1XYZ WER 22

 理解:根据User的firstname进行排序

3. Keys as Custom Classes using Comparator

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 1Ani Bha 12Cal YYY 15XYZ WER 22

So, here we see the output is sorted in increasing order of salaries of users.

理解:用Compator类根据员工的薪水高低来进行排序

转载于:https://www.cnblogs.com/Guoyutian/p/5184406.html

你可能感兴趣的文章
我爱 哐 哐 哐,我是哐人类!-【废话区】
查看>>
WinPE启动U盘的制作方法与软件下载(通用PE工具箱/老毛桃/大白菜WinPE)(转载)...
查看>>
行为型设计模式之5--中介者模式
查看>>
Android DevArt6:Android中IPC的六种方式
查看>>
oracle练习题
查看>>
PMP学习感想
查看>>
Zookeeper全解析——Paxos作为灵魂
查看>>
集合-强大的集合工具类:java.util.Collections中未包含的集合工具
查看>>
CSS清除浮动
查看>>
数据库基础-数据库常用命令总结
查看>>
java8 按对象属性值排序
查看>>
[转帖]nvidia nvlink互联与nvswitch介绍
查看>>
[cnblog新闻]历史性时刻:云硬件支出首次高于传统硬件
查看>>
[转帖]Oracle dba_objects和all_objects 最大的区别
查看>>
【转帖】国产x86处理器KX-6000发布
查看>>
RSA算法及其在iOS中的使用
查看>>
04-js的运算符
查看>>
第三天 while循环 及其用法
查看>>
Delphi 10 seattle 去掉自带的代码连接线
查看>>
构建高并发高可用的电商平台架构实践(转)
查看>>