TreeMap 获取Key和Entry的方法

  • 新建时候可以指定排序依据 new TreeMap<>(new Comparator() {})
  • ceilingEntry(TreeMap下的方法),获取就近key的值的键值对(可以取等),向上取整,倒序之后会相反。返回Entry类型
  • lowerEntry方法 返回严格小于给定键的键值对(不可取等)
  • ceilingKey(TreeMap下的方法),获取就近key的值(可以取等),向上取整,倒序之后会相反。返回map中key的类型
  • lowerKey(key) 返回小于key的最近的键值(不可取等)
  • firstEntry/lastEntry返回最小/最大键的键值对
  • tailMap 返回给定键之后的键值对,传入第二个参数可以选择包括传入key,默认为true
  • subMap 返回切割map 可以传入inclusive表示是否包涵
import java.util.Comparator;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

public class TreeMapUse {
    public static void main(String[] args) {
        // 传入比较器说明排序方式
        TreeMap<Integer, String> map = new TreeMap<>(new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                // 升序
                return Integer.compare(o1, o2);
            }
        });

        map.put(2, "aaa");
        map.put(18, "aaa");
        map.put(4, "aaa");
        map.put(15, "aaa");
        map.put(7, "aaa");

        System.out.println(map);

        // ceilingEntry(TreeMap下的方法),获取就近key的值的键值对(可以取等),向上取整,倒序之后会相反。返回Entry类型
        Map.Entry<Integer, String> ceil = map.ceilingEntry(5);
        System.out.println(ceil);
        // lowerEntry方法 返回严格小于给定键的键值对(不可取等)
        Map.Entry<Integer, String> lower = map.lowerEntry(7);
        System.out.println(lower);
        // ceilingKey(TreeMap下的方法),获取就近key的值(可以取等),向上取整,倒序之后会相反。返回map中key的类型
        Integer ceilKey = map.ceilingKey(9);
        System.out.println(ceilKey);
        //向下取,不可取等
		Integer lowKey = map.lowerKey(9);
		system.out.println(lowKey);

        // 返回最小/最大键的键值对
        Map.Entry<Integer, String> min = map.firstEntry(); // 最小,相应还有firstKey()
        Map.Entry<Integer, String> max = map.lastEntry();  // 最大 相应还有lastKey()

        System.out.println("min---- " + min + "   max---- " + max);

        // tailMap 返回给定键之后的键值对,传入第二个参数可以选择包括传入key,默认为true
        SortedMap<Integer, String> tailMap = map.tailMap(7);
        System.out.println(tailMap);

        // subMap 返回切割map 可以传入inclusive表示是否包涵
        SortedMap<Integer, String> subMap = map.subMap(7, true, 18,true);
        System.out.println(subMap);
    }
}

————————————————
版权声明:本文为CSDN博主「noobmantest」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/weixin_43960044/article/details/116459372

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值