TreeMap集合之传入比较器

package com.day15.Map;

import java.util.Comparator;
import java.util.TreeMap;

import com.day15.bean.Student;

public class TreeMapOne {

  public static void main(String[] args) {
    TreeMap<Student, String> tm=new TreeMap<>(new Comparator<Student>() {

      @Override
      public int compare(Student s1, Student s2) {
        int num=s1.getName().compareTo(s2.getName());
        return num==0 ? s1.getAge()-s2.getAge() :num;
      }

    });
  tm.put(new Student("Kobe",20), "LA");
  tm.put(new Student("KG",21), "Boston");
  tm.put(new Student("PP",22), "Boston");
  tm.put(new Student("Allen",23), "Nanjing");
  System.out.println(tm);//{Student [name=Allen,age=23]=Nanjing, Student [name=KG,age=21]=Boston, Student [name=Kobe,age=20]=LA, Student                                                                                                                                                                                                                                  [name=PP,age=22]=Boston}

  }
}

猜你喜欢

转载自www.cnblogs.com/zhujialei123/p/9038090.html
0条评论
添加一条新回复