Collections用法整理_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > Collections用法整理

Collections用法整理

 2014/10/22 21:41:53  MouseLearnJava  程序员俱乐部  我要评论(0)
  • 摘要:Collections(java.util.Collections)工具类包含了很多有关集合操作的静态方法,使用这些方法能帮我们简化代码。本文将整理Collections工具类的一些基本方法。1.获取List中的最小值List<Integer>intList=Arrays.asList(33,24,18,6,9,99);//6System.out.println(java.util.Collections.min(intList));2.获取List中的最大值List<
  • 标签:用法

Collections?(java.util.Collections) 工具类包含了很多有关集合操作的静态方法,使用这些方法能帮我们简化代码。

本文将整理Collections工具类的一些基本方法。

1. 获取List中的最小值

?

class="java">List<Integer> intList = Arrays.asList(33, 24, 18, 6, 9, 99);
// 6
System.out.println(java.util.Collections.min(intList));

?2. 获取List中的最大值

?

?

List<Integer> intList = Arrays.asList(33, 24, 18, 6, 9, 99);
// 99
System.out.println(java.util.Collections.max(intList));

?

?

3. Shuffle

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);

?

4. nCopies

该方法用于返回一个不可变列表组成的n个拷贝的指定对象。

?

// 生成一个由10个100组成的整数列表
List<Integer> nCopiesList = Collections.nCopies(10, 100);
//[100, 100, 100, 100, 100, 100, 100, 100, 100, 100]
    System.out.println(nCopiesList);

?

5. sort

该方法用于对集合排序。

?

List<Integer> intList = Arrays.asList(33, 24, 18, 6, 9, 99);
Collections.sort(intList);

?

?

?

上述例子没有包含Comparator参数,。我们也可以结合Comparator对对象集合进行排序。 比如对存放Person类的对象集按照年龄进行排序。

?

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;
    }
 
}

?

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);

?

?

? ?

6. binarySearch

?

   List<Integer> intList = Arrays.asList(33, 24, 18, 6, 9, 99);
// 2
System.out.println(Collections.binarySearch(intList, 18));
?

?

7. copy

用两个参数,一个目标 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]
?
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);
? 8. disJoint

用于检查两个集合有无相同的元素,如果没有则返回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);
?

?

?

9. fill

使用指定元素替换指定列表中的所有元素

?

List<String> testList = Arrays.asList("A", "B", "C", "D");
Collections.fill(testList, "Z");
// [Z, Z, Z, Z]
System.out.println(testList);
?

?

?

10. frequency

获取某个元素在集合中出现的次数。

?

List<String> testList = Arrays.asList("A", "B", "C", "D");
int freq = Collections.frequency(testList, "A");
// 1
System.out.println(freq);
?

?

?

11. indexOfSubList

返回指定源列表中第一次出现指定目标列表的起始位置

?

int index = Collections.indexOfSubList(Arrays.asList("A", "B", "C"),
                Arrays.asList("B"));
        // Print 1
        System.out.println(index);
?

?

?

12. lastIndexOfSubList

返回指定源列表中最后一次出现指定目标列表的起始位置

?

int lastIndex = Collections.lastIndexOfSubList(
        Arrays.asList("A", "B", "C", "B"), Arrays.asList("B"));
// Print 3
System.out.println(lastIndex);
?

?

?

13. emptyXXX

请参考之前的文章?http://thecodesample.com/?p=80

?

14. checkedXXX

?

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);
?

?

15. reverse

反转列表中的元素顺序。

?

List<String> reverseCandidate = Arrays.asList("A", "B", "C");
        Collections.reverse(reverseCandidate);
        // [C, B, A]
        System.out.println(reverseCandidate);
?

?

?

16. replaceAll

?

List<String> replaceAllCandidate = Arrays.asList("A", "B", "C");
        // 将A用Z代替
        Collections.replaceAll(replaceAllCandidate, "A", "Z");
        // [Z, B, C]
        System.out.println(replaceAllCandidate);
?

?

17. swap

指定一个目标集合以及两个元素的索引,交换这两个指定位置元素的值。

?

List<String> swapCandidate = Arrays.asList("A", "B", "C");
        // 首尾元素交换
        Collections.swap(swapCandidate, 0, 2);
        // [C, B, A]
        System.out.println(swapCandidate);
?

?

18. synchronizedXXX

?

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>());
?

?

19. unmodifiableXXX

?

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)
?

?

20. singletonXXX

?

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);
?

?

?

21. rotate

根据指定的距离循环移动指定列表中的元素

?

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);
?

?

?

22. reverseOrder

?

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);
?

?

?

?

本文转自http://thecodesample.com/?p=122

更多程序实例请访问http://thecodesample.com/

发表评论
用户名: 匿名