其他分享
首页 > 其他分享> > 集合9、集合_Map接口_TreeMap类

集合9、集合_Map接口_TreeMap类

作者:互联网

TreeMap的排序方式

package map;

import org.junit.jupiter.api.Test;

import java.util.Comparator;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeMap;

/**
 * @author HUTAO
 * @Description
 * @date 2021/10/23 16:45
 */
public class TreeMapTest {

    //向TreeMap中添加key-value,要求key必须是由同一个类创建的对象

    //自然排序
    @Test
    public void test1() {
        TreeMap map = new TreeMap();
        User u1 = new User("Tom", 15);
        User u2 = new User("Jake", 23);
        User u3 = new User("Roy", 22);
        User u4 = new User("Andy", 18);

        map.put(u1, 98);
        map.put(u2, 96);
        map.put(u3, 95);
        map.put(u4, 100);

        Set entrySet = map.entrySet();
        Iterator iterator2 = entrySet.iterator();
        while (iterator2.hasNext()) {
            System.out.println(iterator2.next());
        }
    }


    //定制排序
    @Test
    public void test2() {
        TreeMap map = new TreeMap(new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                if (o1 instanceof User && o2 instanceof User) {
                    User u1 = (User) o1;
                    User u2 = (User) o2;
                    return Integer.compare(u1.getAge(), u2.getAge());
                }
                throw new RuntimeException("输入的类型不匹配!");
            }
        });

        User u1 = new User("Tom", 15);
        User u2 = new User("Jake", 23);
        User u3 = new User("Roy", 22);
        User u4 = new User("Andy", 18);

        map.put(u1, 98);
        map.put(u2, 96);
        map.put(u3, 95);
        map.put(u4, 100);

        Set entrySet = map.entrySet();
        Iterator iterator2 = entrySet.iterator();

        while (iterator2.hasNext()) {
            System.out.println(iterator2.next());
        }

    }


}

标签:Map,map,entrySet,TreeMap,put,User,集合,new
来源: https://www.cnblogs.com/yukiasuna/p/15579830.html