TreeMap的学习

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.

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 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进行排序

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 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类根据员工的薪水高低来进行排序

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值