有序的TreeSet和TreeMap

有序的TreeSet和TreeMap

package myTest;

import java.util.Comparator;
import java.util.Map.Entry;
import java.util.TreeMap;
import java.util.TreeSet;

public class Test15_有序的TreeSet和TreeMap {

	public static void main(String[] args) {
		
		TreeSet<String> set1=new TreeSet<>();
		
		set1.add("dad");
		set1.add("ewqeq");
		set1.add("fsfe");
		set1.add("mjh");
		set1.add("fgh");
		set1.add("plj");
		set1.add("aasdf");
		//String类型默认按照字符顺序
		for (String s : set1) {
			System.out.println(s);
		}
		System.out.println("-------------------------");
		
		//自定义Class类型必须定义比较器
		TreeSet<Student> set=new TreeSet<Student>(new Comparator<Student>(){
			@Override
			public int compare(Student o1, Student o2) {
				return o1.score > o2.score ? 1 : (o1.score == o2.score ? 0 : -1);
			}
		});
		
		set.add(new Student(12, 99, 182));
		set.add(new Student(13, 90, 182));
		set.add(new Student(14, 83, 174));
		set.add(new Student(14, 50, 178));
		set.add(new Student(16, 70, 185));
		set.add(new Student(16, 57, 170));
		for (Student student : set) {
			System.out.println(student);
		}
		
		System.out.println("=======================");
		
		
		TreeMap<String, Integer> map1=new TreeMap<>();
		map1.put("weqw", 1);
		map1.put("asda", 2);
		map1.put("zsa", 3);
		map1.put("qw", 5);
		map1.put("fd", 4);
		//key为String类型,默认按照字符顺序
		for (Entry<String,Integer> entry : map1.entrySet()) {
			System.out.println(entry.getKey()+","+entry.getValue());
		}
		System.out.println("---------------");
		
		//key为自定义Class类型,必须定义比较器
		TreeMap<Student, Integer> map2=new TreeMap<>(new Comparator<Student>(){
			@Override
			public int compare(Student o1, Student o2) {
				return o1.score > o2.score ? 1 : (o1.score == o2.score ? 0 : -1);
			}
		});
		map2.put(new Student(12, 99, 182), 1);
		map2.put(new Student(13, 90, 182), 2);
		map2.put(new Student(14, 83, 174), 3);
		map2.put(new Student(16, 70, 185), 5);
		map2.put(new Student(16, 57, 170), 4);
		
		for (Entry<Student, Integer> entry : map2.entrySet()) {
			System.out.println(entry.getKey()+","+entry.getValue());
		}
		
	}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值