The association use of HashMap, TreeMap and Comparable, Comparator in Java

    We know that in the Map interface, the HashMap class stores the elements according to the hashcode of the key of the element. The key- value pair stored in the HashMap is random when it is retrieved. It stores data according to the HashCode value of the key. Get its value directly, with fast access speed. Insert, delete and locate elements in Map, HashMap is the best choice. But if you want to sort the elements in a custom order, you need to use a TreeMap.

    TreeMap is not stored according to hashcode, but according to the compareTo method of the implemented compareable interface. As long as the return result of compareTo is 0, it means that the two objects are equal, then the two objects cannot be stored, and the later put will put Cover the front.

1. Sort by implementing the comparable interface

First create the TestPerson class

import java.util.Objects;

public class TestPerson implements Comparable{
	private String name;
	private Integer age;
	TestPerson(String name,int age){
		this.name = name;
		this.age = age;
	}
	public String getName(){
		return this.name;
	}
	public int getAge(){
		return this.age;
	}
	@Override
	public boolean equals(Object o){
		if(o instanceof TestPerson){
			TestPerson p = (TestPerson) o;
			return this.name.equals(p.name) && this.age==p.age;
		}
		else
			return false;
	}
    @Override  
    public int hashCode() {  
        return Objects.hash(name, age);  
    }
	@Override
	public int compareTo(Object o) {
		// TODO Auto-generated method stub
		TestPerson tp = (TestPerson) o;
		return this.age > tp.getAge() ? 1 : this.age == tp.getAge() ? 0 : -1;
	}
	@Override
	public String toString() {
		// TODO Auto-generated method stub
		return name + "(" + age.toString() + ")";
	}
}

Test case:

import java.util.Map;
import java.util.TreeMap;
 
public class TreeMapTest {
	public static void main(String[] args) {
		Map<TestPerson,String> m = new TreeMap<TestPerson,String>();
		m.put(new TestPerson("Jack Ma",51),"Alibaba");
		m.put(new TestPerson("Jackey Cheng",60), "YaolaiYingCheng");
		m.put(new TestPerson("Jay Chou",35),"YeHuimei");
		m.put(new TestPerson("Ma Huateng",53),"Tencent");
		System.out.println(m);
	}	
}

output:

{Jay Chou(35)=YeHuimei, Jack Ma(51)=Alibaba, Ma Huateng(53)=Tencent, Jackey Cheng(60)=YaolaiYingCheng}

2. Sort by implementing the comparator interface

The previous example is sorted by age, this example is sorted by name

import java.util.Comparator;
import java.util.Objects;

public class TestPerson implements Comparator<TestPerson>{
	private String name;
	private Integer age;
	public TestPerson(String name,int age){
		this.name = name;
		this.age = age;
	}
	public TestPerson () {
		
	}
	public String getName(){
		return this.name;
	}
	public int getAge(){
		return this.age;
	}
	@Override
	public boolean equals(Object o){
		if(o instanceof TestPerson){
			TestPerson p = (TestPerson) o;
			return this.name.equals(p.name) && this.age==p.age;
		}
		else
			return false;
	}
    @Override  
    public int hashCode() {  
        return Objects.hash(name, age);  
    }
	@Override
	public String toString() {
		// TODO Auto-generated method stub
		return name + "(" + age.toString() + ")";
	}
	@Override
	public int compare (TestPerson p1, TestPerson p2) {
		// TODO Auto-generated method stub
		//return p1.getAge()>p2.getAge()? 1 : p1.getAge() == p2.getAge()? 0:-1;
		return p1.getName().compareTo(p2.getName());
	}
}

test case

import java.util.Map;
import java.util.TreeMap;
 
public class TreeMapTest {
	public static void main(String[] args) {
		Map<TestPerson,String> m = new TreeMap<TestPerson,String>(new TestPerson());
		m.put(new TestPerson("Jack Ma",51),"Alibaba");
		m.put(new TestPerson("Jackey Cheng",60), "YaolaiYingCheng");
		m.put(new TestPerson("Jay Chou",35),"YeHuimei");
		m.put(new TestPerson("Ma Huateng",53),"Tencent");
		System.out.println(m);
	}	
}

output

{Jack Ma(51)=Alibaba, Jackey Cheng(60)=YaolaiYingCheng, Jay Chou(35)=YeHuimei, Ma Huateng(53)=Tencent}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325520101&siteId=291194637