集合工具类Collections

集合工具类Collections

1.基本信息:

包:java,util
类型:类/包装器
如果为此类的方法所提供的 collection 或类对象为 null,则这些方法都将抛出 NullPointerException。

在这里插入图片描述

2.常用方法

2.1添加

// 将所有指定元素添加到指定 collection 中
addAll(Collection<? super T> c, T... elements)

2.2查找

//使用二分搜索法搜索指定列表,以获得指定对象。
binarySearch(List<? extends Comparable<? super T>> list, T key)

//使用比较器二分搜索法搜索指定列表,以获得指定对象。
binarySearch(List<? extends T> list, T key, Comparator<? super T> c)

//返回指定源列表中第一次出现指定目标列表的起始位置;如果没有出现这样的列表,则返回 -1。
indexOfSubList(List<?> source, List<?> target)

2.3排序

//根据指定比较器产生的顺序,返回给定 collection 的最大元素。
max(Collection<? extends T> coll, Comparator<? super T> comp)

// 根据元素的自然顺序 对指定列表按升序进行排序。
sort(List<T> list)

String [] str = new String[]{"sdf","dsg","tyf","rjtk","ijg","ghhd","guisd"};

List list =Arrays.asList(str);
System.out.println(list);

Collections.sort(list);
System.out.println(list);

>>>[sdf, dsg, tyf, rjtk, ijg, ghhd, guisd]
   [dsg, ghhd, guisd, ijg, rjtk, sdf, tyf]

//根据指定比较器产生的顺序对指定列表进行排序。
sort(List<T> list, Comparator<? super T> c)

//反转指定列表中元素的顺序。
reverse(List<?> list)

String [] str = new String[]{"sdf","dsg","tyf","rjtk","ijg","ghhd","guisd"};

List list =Arrays.asList(str);
System.out.println(list);

Collections.sort(list);
Collections.reverse(list);
System.out.println(list);

>>>[sdf, dsg, tyf, rjtk, ijg, ghhd, guisd]
   [tyf, sdf, rjtk, ijg, guisd, ghhd, dsg]

//随机打乱列表内元素顺序
public static void shuffle(List<?> list,Random rnd)

String [] str = new String[]{"sdf","dsg","tyf","rjtk","ijg","ghhd","guisd"};

List list =Arrays.asList(str);
System.out.println(list);

Collections.shuffle(list);
System.out.println(list);

>>>[sdf, dsg, tyf, rjtk, ijg, ghhd, guisd]
   [ghhd, rjtk, tyf, sdf, ijg, guisd, dsg]  //(随机出现的,不一定是这个)

2.4比较

//如果两个指定 collection 中没有相同的元素,则返回 true。
disjoint(Collection<?> c1, Collection<?> c2)

//返回指定 collection 中等于指定对象的元素数。
frequency(Collection<?> c, Object o)

2.5替换

//使用指定元素替换指定列表中的所有元素。
fill(List<? super T> list, T obj)

//使用另一个值替换列表中出现的所有某一指定值。
replaceAll(List<T> list, T oldVal, T newVal)

//在指定列表的指定位置处交换元素。
swap(List<?> list, int i, int j)

2.6移动

//根据指定的距离轮换指定列表中的元素。
rotate(List<?> list, int distance)
假设 list 包含 [a, b, c, d, e]。要将索引 1 处的元素(b)向前移动两个位置,请执行以下调用:
Collections.rotate(list.subList(1, 4), -1);
得到的列表是 [a, c, d, b, e]。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值