Collections类:java.util.Collections类主要提供了对集合操作或者返回集合的静态方法。
常用方法
方法 | 功能 |
---|
static <T extends Object & Comparable<? super T>> T max(Collection<? extends T> coll) | 根据元素的自然顺序返回给定集合的最大元素 |
static T max(Collection<? extends T> coll, Comparator<?super T> comp) | 根据指定比较器引发的顺序返回给定集合的最大元素 |
static <T extends Object & Comparable<? super T>> T min(Collection<? extends T> coll) | 根据元素的自然顺序返回给定集合的最小元素 |
static T min(Collection<? extends T> coll, Comparator<?super T> comp) | 根据指定比较器引发的顺序返回给定集合的最小元素 |
static void copy(List<? super T> dest, List<? extends T> src) | 将一个列表中的所有元素复制到另一个列表中 |
static void reverse(List<?> list) | 反转指定列表中元素的顺序 |
static void shuffle(List<?> list) | 使用默认的随机源随机置换指定的列表 |
static <T extends Comparable<? super T>> void sort(List list) | 根据其元素的自然顺序将指定列表按升序排序 |
static void sort(List list, Comparator<? super T> c) | 根据指定比较器指定的顺序对指定列表进行排序 |
static void swap(List<?> list, int i, int j) | 交换指定列表中指定位置的元素 |
具体方法如下:
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class CollectionsTest {
public static void main(String[] args) {
Integer[] s1 = new Integer[]{10, 50, 42, 30, 21};
List<Integer> l1 = Arrays.asList(s1);
System.out.println(l1);
System.out.println("集合中的最大值为" + Collections.max(l1));
Comparator<Integer> comparatorMax = new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o1 - o2;
}
};
System.out.println("通过比较器获取的最大值结果为" + Collections.max(l1, comparatorMax));
System.out.println("集合中的最小值为" + Collections.min(l1));
Comparator<Integer> comparatorMin = new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o1 - o2;
}
};
System.out.println("通过比较器获取的最小值结果为" + Collections.min(l1, comparatorMin));
List<Integer> l2 = Arrays.asList(new Integer[10]);
Collections.copy(l2, l1);
System.out.println("复制后集合中的元素为" + l2);
Collections.reverse(l1);
System.out.println("反转后的结果为" + l1);
Collections.shuffle(l1);
System.out.println("随机置换后的结果为" + l1);
Collections.sort(l1);
System.out.println("升序后的排列结果为" + l1);
Comparator<Integer> comparatorSort = new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o2 - o1;
}
};
Collections.sort(l1, comparatorSort);
System.out.println("比较器排序后的结果为" + l1);
Collections.swap(l1, 1, 3);
System.out.println("交换集合中元素位置后的结果为" + l1);
}
}