【笔记】Java的Collections

前言

Java的Collections学习笔记

排序集合

  • 正序排序集合
  • 排序后会修改原集合,而不是返回新集合
1
Collections.sort(list);

指定排序规则

1
2
3
Collections.sort(list, (Object o1, Object o2) -> {
return o1.compareTo(o2);
});

根据二分搜索法搜索集合中的元素所在下标

1
int index = Collections.binarySearch(list, <value>);

逆序集合

1
Collections.reverse(list);

随机打乱集合

1
Collections.shuffle(list);

指定随机种子

1
Collections.shuffle(list, new Random(<seed>));

交换元素

  • 根据下标交换元素位置
1
Collections.swap(list, <index_1>, <index_2>);

填充集合

1
Collections.fill(list, <value>);

拷贝集合内的所有元素

  • 目标集合长度需大于等于被拷贝的集合长度
  • 目标集合内超出被拷贝集合长度的元素不会被修改
1
Collections.copy(list, <target_list>);

获取集合的最小值

1
Collections.min(list);

指定排序规则

1
2
3
Collections.min(list, (Object o1, Object o2) -> {
return o1.compareTo(o2);
});

获取集合的最大值

1
Collections.max(list);

指定排序规则

1
2
3
Collections.max(list, (Object o1, Object o2) -> {
return o1.compareTo(o2);
});

替换指定下标的元素

  • 如果至少替换了一个元素,则返回true
1
boolean success = Collections.replaceAll(list, <value_old>, <value_new>);

搜索子集合

  • 搜索子集合在父元素第一次出现时的开始位置下标

从头部搜索指定子集合

1
2
3
4
List father = new ArrayList();
List son = new ArrayList();

int index = Collections.indexOfSubList(father, son);

从尾部搜索指定子集合

1
2
3
4
List father = new ArrayList();
List son = new ArrayList();

int index = Collections.lastIndexOfSubList(father, son);

获取只读空集合

通过常量获取

1
List list = Collections.EMPTY_LIST;
1
Set set = Collections.EMPTY_SET;
1
Map map = Collections.EMPTY_MAP;

通过方法获取

1
List list = Collections.emptyList();
1
Set set = Collections.emptySet();
1
Map map = Collections.emptyMap();

获取只读单元素集合

1
List list = Collections.singletonList();
1
Set set = Collections.singleton();
1
Map map = Collections.singletonMap();

批量添加元素

  • 在集合尾部批量添加元素
  • 如果集合发生改变,则返回true
1
boolean success = Collections.addAll(list, <value1>, <value2>);

完成