java基础笔记11-TreeSet-集合

TreeSet通过构造方法实现自定义排序

TreeSet treeSet = new TreeSet(new Comparator() {
    @Override
    public int compare(Object o1, Object o2) {
        return ((String) o1).length() - ((String) o2).length();
    }
});
treeSet.add("bbb");
treeSet.add("a");
treeSet.add("ee");
treeSet.add("cccc");
System.out.println(treeSet);

TreeMap通过构造方法实现自定义排序

TreeMap<String, String> map = new TreeMap<>(new Comparator<String>() {
    @Override
    public int compare(String o1, String o2) {
        return o1.length() - o2.length();
    }
});
map.put("aaa", "cat");
map.put("bb", "pig");
map.put("c", "pig");
System.out.println(map);

Collections工具类

  • Collections是一个可以操作Set、List、Map等的工具类
  • 提供了一系列静态方法对集合元素进行查询、修改和排序等操作

排序操作

  • 反转list:Collections.reverse(list)
  • 对集合进行随机排序: Collections.shuffle(list)
  • 根据元素的自然顺序对指定集合的元素进行排序:Collections.sort(list)
  • 根据指定的Comparator产生的顺序对指定的集合元素排序
Collections.sort(list, new Comparator() {
	@Override
	public int compare(Object o1, Object o2) {
		return ((String)o1).length() - ((String)o2).length();
	}
})
  • swap(list, int i, int j):将指定list集合中的i和j元素交换
  • Collections.max(list):根据元素的自然顺序返回给定集合中的最大元素
  • Collections.max(Collection, comparator):根据Comparator指定的顺序,返回集中中最大的元素
  • Collections.min(list):根据元素的自然顺序返回给定集合中的最小元素
  • Collections.min(Collection, comparator):根据Comparator指定的顺序,返回集中中最小的元素
  • Collections.frequency(Collection, object):返回指定集合中指定元素出现的次数
  • Collections.copy(dest, list):把list中的元素拷贝到dest中
  • Collections.replaceAll(list, oldVal, newVal):把list中oldVal用newVal代替
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值