Collections (java.util.Collections) 工具类包含了很多有关集合操作的静态方法,使用这些方法能帮我们简化代码。
本文将整理Collections工具类的一些基本方法。
目录
Java代码
List<Integer> intList = Arrays.asList(33, 24, 18, 6, 9, 99);
// 6
System.out.println(java.util.Collections.min(intList));
Java代码
List<Integer> intList = Arrays.asList(33, 24, 18, 6, 9, 99);
// 99
System.out.println(java.util.Collections.max(intList));
Shuffle方法可以使一个集合的元素乱序化。比如,一副牌的集合为cardList (类型List<Card>), 使用Collections.shuffle(cardList)就能使一副牌处于乱序,达到洗牌的目的。
List<Integer> intList = Arrays.asList(33, 24, 18, 6, 9, 99);
Collections.shuffle(intList);
// 一次测试的结果
// [6, 18, 33, 24, 99, 9]
System.out.println(intList);
该方法用于返回一个不可变列表组成的n个拷贝的指定对象。
Java代码
// 生成一个由10个100组成的整数列表
List<Integer> nCopiesList = Collections.nCopies(10, 100);
//[100, 100, 100, 100, 100, 100, 100, 100, 100, 100]
System.out.println(nCopiesList);
该方法用于对集合排序。
Java代码
List<Integer> intList = Arrays.asList(33, 24, 18, 6, 9, 99);
Collections.sort(intList);
上述例子没有包含Comparator参数,。我们也可以结合Comparator对对象集合进行排序。 比如对存放Person类的对象集按照年龄进行排序。
Java代码
package com.thecodesmaple.example.collection;
public class Person {
private int age;
private String firstName;
private String lastName;
public Person(int age, String firstName, String lastName) {
this.age = age;
this.firstName = firstName;
this.lastName = lastName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String toString() {
return "Age: " + age + " FirstName " + firstName + " LastName: "
+ lastName;
}
}
Java代码
List<Person> personList = Arrays.asList(new Person(21, "Eric", "W"),
new Person(17, "John", "A"), new Person(28, "Allan", "H"),
new Person(15, "Jonas", "B"));
// [Age: 21 FirstName Eric LastName: W, Age: 17 FirstName John LastName:
// A, Age: 28 FirstName Allan LastName: H, Age: 15 FirstName Jonas
// LastName: B]
System.out.println(personList);
Collections.sort(personList, new Comparator<Person>() {
@Override
public int compare(Person p1, Person p2) {
return p1.getAge() - p2.getAge();
}
});
// [Age: 15 FirstName Jonas LastName: B, Age: 17 FirstName John
// LastName: A, Age: 21 FirstName Eric LastName: W, Age: 28 FirstName
// Allan LastName: H]
System.out.println("按照年龄排序后:");
System.out.println(personList);
Java代码
此法为二分搜索法,故查询前需要用sort()方法将数组排序,如果数组没有排序,则结果是不确定的,另外,如果数组中含有多个指定值的元素,则无法保证找到的是哪一个。
//如果key在数组中,则返回搜索值的索引;否则返回-1或者”-“(插入点)。插入点是索引键将要插入数组的那一点,即第一个大于该键的元素索引。
List<Integer> intList = Arrays.asList(33, 24, 18, 6, 9, 99);
System.out.println(Collections.binarySearch(intList, 18));
System.out.println(Collections.binarySearch(intList, 10));
用两个参数,一个目标 List 和一个源 List, 将源的元素拷贝到目标,并覆盖它的内容。目标 List至少与源一样长。
List<String> listOne = Arrays.asList("A", "B", "C", "D");
List<String> listTwo = Arrays.asList("X", "Y", "Z");
Collections.copy(listOne, listTwo);
System.out.println(listOne);// [X, Y, Z, D]
System.out.println(listTwo);//[X, Y, Z]
用于检查两个集合有无相同的元素,如果没有则返回true。
List<String> list3 = Arrays.asList("A", "B", "C", "D");
List<String> list4 = Arrays.asList("X", "Y", "Z");
boolean disJoint = Collections.disjoint(list3, list4);
// true
System.out.println(disJoint);
使用指定元素替换指定列表中的所有元素
List<String> testList = Arrays.asList("A", "B", "C", "D");
Collections.fill(testList, "Z");
// [Z, Z, Z, Z]
System.out.println(testList);
获取某个元素在集合中出现的次数。
List<String> testList = Arrays.asList("A", "B", "C", "D");
int freq = Collections.frequency(testList, "A");
// 1
System.out.println(freq);
返回指定源列表中第一次出现指定目标列表的起始位置
int index = Collections.indexOfSubList(Arrays.asList("A", "B", "C"),
Arrays.asList("B"));
// Print 1
System.out.println(index);
返回指定源列表中最后一次出现指定目标列表的起始位置
nt lastIndex = Collections.lastIndexOfSubList(
Arrays.asList("A", "B", "C", "B"), Arrays.asList("B"));
// Print 3
System.out.println(lastIndex);
Collections.emptyList()、emptySet()、emptyMap()
new ArrayList() 或者 new LinkedList() 在创建的时候有会有初始大小,多少会占用一内存。但是Collections.emptyList()却不会
public class ListTest {
private static final int printCount = 10000;
public static void main(String[] args) {
long freeMemory = Runtime.getRuntime().freeMemory();
System.out.println("freeMemory: " + freeMemory);
for (int i = 0; i < printCount; i++) {
List newList = new ArrayList();
}
long freeMemoryNew=Runtime.getRuntime().freeMemory();
System.out.println("freeMemory use: "+(freeMemory-freeMemoryNew));
for(int i = 0;i < printCount; i++){
List emptyList = Collections.emptyList();
}
long freeMemoryEmpty = Runtime.getRuntime().freeMemory();
System.out.println("freeMemory use: "+(freeMemoryNew-freeMemoryEmpty));
}
}
Connected to the target VM, address: '127.0.0.1:63534', transport: 'socket'
Disconnected from the target VM, address: '127.0.0.1:63534', transport: 'socket'
freeMemory: 253398816
freeMemory use: 1430376
freeMemory use: 0
Process finished with exit code 0
我们可以看出new ArrayList执行一万次会消耗1430376KB内存,而Collections.emptyList不会消耗内存,那有人会说emptyList不也是new EmptyList()吗?其实我们再仔细看下上面的源码就发现emptyList是一个static变量,只会初始化一次,所以后续使用不会再初始化对象。此时我们可以得出结论,emptyList不占用内存,但是无法执行add等方法,new ArrayList()占用内存,但是会初始化对象数组,可以执行add等方法
Java代码
List<String> stringList = Arrays.asList("A", "B", "C", "D");
List<String> typeSafeList = Collections.checkedList(stringList, String.class);
//[A, B, C, D]
System.out.println(typeSafeList);
反转列表中的元素顺序。
Java代码
List<String> reverseCandidate = Arrays.asList("A", "B", "C");
Collections.reverse(reverseCandidate);
// [C, B, A]
System.out.println(reverseCandidate);
Java代码
List<String> replaceAllCandidate = Arrays.asList("A", "B", "C");
// 将A用Z代替
Collections.replaceAll(replaceAllCandidate, "A", "Z");
// [Z, B, C]
System.out.println(replaceAllCandidate);
指定一个目标集合以及两个元素的索引,交换这两个指定位置元素的值。
Java代码
List<String> swapCandidate = Arrays.asList("A", "B", "C");
// 首尾元素交换
Collections.swap(swapCandidate, 0, 2);
// [C, B, A]
System.out.println(swapCandidate);
Java代码
Collection<String> c = Collections.synchronizedCollection(new ArrayList<String>());
List<String> list = Collections.synchronizedList(new ArrayList<String>());
Set<String> set = Collections.synchronizedSet(new HashSet<String>());
Map<String, String> m = Collections.synchronizedMap(new HashMap<String,String>());
Java代码
List<String> unmodifiableList = Collections.unmodifiableList(Arrays
.asList("A", "B", "C"));
unmodifiableList.add("D");//此动作会抛异常
// Exception in thread "main" java.lang.UnsupportedOperationException
// at java.util.Collections$UnmodifiableCollection.add(Unknown Source)
// at
// com.thecodesmaple.example.collection.CollectionsExample.main(CollectionsExample.java:149)
Java代码
String init[] = { "One", "Two", "Three", "One", "Two", "Three" };
List list1 = new ArrayList(Arrays.asList(init));
List list2 = new ArrayList(Arrays.asList(init));
list1.remove("One");
// [Two, Three, One, Two, Three]
System.out.println(list1);
// [Two, Three, Two, Three]
list2.removeAll(Collections.singleton("One"));
System.out.println(list2);
根据指定的距离循环移动指定列表中的元素
Java代码
List<String> rotateList = Arrays.asList("A", "B", "C", "D", "E", "F");
// [F, A, B, C, D, E]
// Collections.rotate(rotateList, 1);
// System.out.println(rotateList);
Collections.rotate(rotateList, 3);
// [D, E, F, A, B, C]
System.out.println(rotateList);
Java代码
List<String> reverseOrderTest = Arrays.asList("A", "B", "C", "D", "E", "F");
Comparator c = Collections.reverseOrder();
Collections.sort(reverseOrderTest, c);
// [F, E, D, C, B, A]
System.out.println(reverseOrderTest);