Java java.util.Collections类相关方法示例

x33g5p2x  于2021-08-20 转载在 Java  
字(9.3k)|赞(0)|评价(0)|浏览(383)

java.util.Collections类完全由操作或返回集合的静态方法组成。

它包含了对集合进行操作的多态算法、返回由指定集合支持的新集合的 "包装器",以及其他一些零星的方法。
如果提供给该类的集合或类对象为空,该类的方法都会抛出NullPointerException。
在这篇文章中,我们将通过实例来探讨几个有用的集合类方法

java.util.Collections方法

  • sort(List list)
  • sort(List list, Comparator<? super Project> c)
  • shuffle(List<?> list)
  • reverse(List<?> list)
  • rotate(List<?> list, int distance)
  • swap(List<?> list, int i, int j)
  • replaceAll(List list, String oldVal, String newVal)
  • copy(List<? super String> dest, List<? extends String> src)
  • Collections.binarySearch(list, "element 4")
  • frequency(Collection<?> c, Object o)
  • disjoint(Collection> c1, Collection> c2)
  • min(Collection extends?> coll)
  • max(Collection extends ?> coll)

java.util.Collections类

集合类提供了静态方法,其第一个参数是要对其进行操作的集合。Java平台提供的绝大多数算法都是对List实例进行操作,但也有少数算法是对任意的Collection实例进行操作。我们使用集合类来演示以下算法的例子。

  • 排序
  • Shuffling
  • 常规数据操作
  • 搜索
  • Composition
  • 寻找极端值

###使用java.util.Collections类进行排序

集合类提供了两种排序方法。

sort(List list)

根据元素的自然排序,将指定的列表排序为升序。列表中的所有元素必须实现可比较接口。

List<String> list = new LinkedList<>();
list.add("element 2");
list.add("element 1");
list.add("element 4");
list.add("element 3");
// Sorts the specified list into ascending order, according to
// the natural ordering of its elements.
Collections.sort(list);
for (String str : list) {
 System.out.println(" sort elements in ascending order  --" + str);
}

输出:

sort elements in ascending order  --element 1
 sort elements in ascending order  --element 2
 sort elements in ascending order  --element 3
 sort elements in ascending order  --element 4

sort(List list, Comparator<? super Project> c)

根据指定的比较器引起的顺序对指定的列表进行排序。列表中的所有元素必须使用指定的比较器进行相互比较(也就是说,c.compare(e1, e2)不能对列表中的任何元素e1和e2抛出ClassCastException)。例子。

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class CollectionsClassExamples {

 public static void main(String[] args) {
  sortingCustomObjectsByComparator();
 }

 private static void sortingCustomObjectsByComparator() {
  // Sort Projects by project id in ascending order.
  List<Project> projects = new ArrayList<>();
  Project project = new Project();
  project.setProjectId(100);
  project.setProjectName("TMS");
  projects.add(project);

  Project project2 = new Project();
  project2.setProjectId(200);
  project2.setProjectName("APEX");
  projects.add(project2);
  
  Project project3 = new Project();
  project3.setProjectId(50);
  project3.setProjectName("CMS");
  projects.add(project3);

  // Sorting project by project name in ascending order in Java
  Collections.sort(projects, Comparator.comparing(Project::getProjectName));
  printList(projects);

 }

 private static void printList(List<Project> projects) {
  for (Project project : projects) {
   System.out.println(project.getProjectId());
   System.out.println(project.getProjectName());
  }
 }

}

class Project implements Comparable<Project> {
 private int projectId;
 private String projectName;

 public int getProjectId() {
  return projectId;
 }

 public void setProjectId(int projectId) {
  this.projectId = projectId;
 }

 public String getProjectName() {
  return projectName;
 }

 public void setProjectName(String projectName) {
  this.projectName = projectName;
 }

 @Override
 public int compareTo(Project project) {
  return this.getProjectId() - project.getProjectId();
 }
}

输出:

200
APEX
50
CMS
100
TMS

###使用java.util.Collections类进行洗牌

shuffle算法的作用与sort相反,它破坏了List中可能存在的任何顺序的痕迹。也就是说,该算法基于来自随机性源的输入对List进行重新排序,假设随机性源是公平的,那么所有可能的排列组合都会以相同的可能性出现。Collections utility类提供了洗牌方法。

shuffle(List<?> list)

使用默认的随机性源对指定的列表进行随机排列。所有的排列都以近似的可能性发生。

例子。

private static void shuffleAlgorithmsDemo() {
 List<String> list = new LinkedList<>();
 list.add("element 2");
 list.add("element 1");
 list.add("element 4");
 list.add("element 3");

 Collections.sort(list);
 for (String str : list) {
  System.out.println(" sort elements in ascending order  --" + str);
 }

 // randomly permutes the elements in a List.
 Collections.shuffle(list);
 for (String str : list) {
  System.out.println(" sort elements in ascending order  --" + str);
 }
}

输出。

sort elements in ascending order  --element 2
 sort elements in ascending order  --element 3
 sort elements in ascending order  --element 4
 shuffle elements  --element 1
 shuffle elements  --element 3
 shuffle elements  --element 4
 shuffle elements  --element 2

常规数据操作

Collections类提供了五种算法来对List对象进行常规的数据操作,所有这些算法都是非常直接的。

  • reverse - 颠倒List中元素的顺序。
  • fill - 用指定的值覆盖List中的每个元素。这个操作对于重新初始化List非常有用。
  • copy - 接收两个参数,一个目标列表和一个源列表,并将源列表中的元素复制到目标列表中,覆盖其内容。目标列表必须至少和源列表一样长。如果它更长,目标列表中的剩余元素不受影响。
  • swap - 交换列表中指定位置的元素。
  • addAll - 将所有指定的元素添加到一个集合中。要添加的元素可以单独指定或者作为一个数组。

reverse(List<?> list)

反转指定列表中的元素的顺序。

例子。

List<String> list = new LinkedList<>();
list.add("element 2");
list.add("element 1");
list.add("element 4");
list.add("element 3");

Collections.sort(list);
for(String str : list){
  System.out.println(" sort elements in ascending order  --" + str);
}
//reverses the order of the elements in a List.
Collections.reverse(list);

rotate(List<?> list, int distance)

将指定列表中的元素按指定距离旋转。调用此方法后,在索引i处的元素将是先前在索引(i - distance)mod list.size()处的元素,对于i的所有值在0和list.size()-1之间,包括在内。(这个方法对列表的大小没有影响。)

例子。

List<String> list = new LinkedList<>();
list.add("element 2");
list.add("element 1");
list.add("element 4");
list.add("element 3");

// rotates all the elements in a List by a specified distance.
Collections.rotate(list, 1);

swap(List<?> list, int i, int j)

交换指定列表中指定位置的元素。(如果指定的位置相等,调用这个方法会使列表保持不变。)

例子。

List<String> list = new LinkedList<>();
list.add("element 2");
list.add("element 1");
list.add("element 4");
list.add("element 3");

//swaps the elements at specified positions in a List.
Collections.swap(list, 0, 1);
printMessage(list, "swap elements ");

replaceAll(List list, String oldVal, String newVal)

用一个指定的值替换列表中的所有出现的值。更正式地说,用newVal替换列表中的每个元素e,使得(oldVal==null ? e==null : oldVal.e equals(e))。(这个方法对列表的大小没有影响)。)

例子。

List<String> list = new LinkedList<>();
list.add("element 2");
list.add("element 1");
list.add("element 4");
list.add("element 3");

//replaces all occurrences of one specified value with another.
Collections.replaceAll(list, "element 3", "element 6");

copy(List<? super String> dest, List<? extends String> src)

将一个列表中的所有元素复制到另一个列表中。操作后,目的列表中每个被复制元素的索引将与源列表中的索引相同。目标列表必须至少和源列表一样长。如果它更长,目标列表中的其余元素不受影响。

例子。

List<String> list = new LinkedList<>();
list.add("element 2");
list.add("element 1");
list.add("element 4");
list.add("element 3");

List<String> destList = new ArrayList<>();
Collections.copy(destList, list);

搜索

binarySearch 算法在一个排序的 List 中搜索一个指定的元素。这个算法有两种形式。 

第一种是接受一个 List 和一个要搜索的元素 ("搜索键")。这种形式假定 List 是根据其元素的自然排序以升序排序的。
第二种形式除了List和搜索键之外,还需要一个比较器,并假定List是按照指定的Comparator进行升序排序的。在调用 binarySearch 之前,可以使用排序算法对 List 进行排序。例子。

private static void searchingAlgorithmsDemo() {
 List<String> list = new LinkedList<>();
 list.add("element 2");
 list.add("element 1");
 list.add("element 4");
 list.add("element 3");
 
 Collections.sort(list);
 for (String str : list) {
  System.out.println(" sort elements in ascending order  --" + str);
 }
 int index = Collections.binarySearch(list, "element 4");
 System.out.println("Element found at ::" + index);
}

输出:

sort elements in ascending order  --element 1
 sort elements in ascending order  --element 2
 sort elements in ascending order  --element 3
 sort elements in ascending order  --element 4
Element found at ::3

组成

frequency 和 disjoint 算法测试一个或多个集合的某些方面的组成。

*频率 - 计算指定元素在指定集合中出现的次数。

  • disjoint - 确定两个集合是否不相交;也就是说,它们是否不包含共同的元素。

frequency(Collection<?> c, Object o)

返回指定集合中等于指定对象的元素的数量。更确切地说,返回集合中元素e的数量,使得(o == null ? e == null : o.e equals(e))。

例子。

List<String> list = new LinkedList<>();
list.add("element 2");
list.add("element 1");
list.add("element 1");
list.add("element 3");
//Returns the number of elements in the specified collection         
//equal to the specified object.
System.out.println(Collections.frequency(list, "element 1"));

disjoint(Collection> c1, Collection> c2)

如果两个指定的集合没有共同的元素,返回true。

例子。

List<String> list = new LinkedList<>();
list.add("element 2");
list.add("element 1");
list.add("element 1");
list.add("element 3");
//Returns the number of elements in the specified collection         
//equal to the specified object.

System.out.println(Collections.frequency(list, "element 1"));
List<String> list2 = new LinkedList<>();
list2.add("element 2");
list2.add("element 1");
list2.add("element 1");
list2.add("element 3");
//Returns true if the two specified collections have no elements in common. 
System.out.println(Collections.disjoint(list, list2));

###寻找极端值(min和max方法)

min 和 max 算法分别返回指定集合中包含的最小和最大元素。这两种操作都有两种形式。 

简单的形式是只接受一个集合,并根据元素的自然排序返回最小(或最大)元素。 
第二种形式除了集合之外,还需要一个Comparator,根据指定的Comparator返回最小(或最大)元素。

min(Collection extends?> coll)

根据元素的自然排序,返回给定集合中的最小元素。集合中的所有元素必须实现Comparable接口。 

此外,集合中的所有元素必须是相互可比的(也就是说,e1.compareTo(e2)不能对集合中的任何元素e1和e2产生ClassCastException)。例子。

List<Integer> list = new LinkedList<>();
list.add(100);
list.add(300);
list.add(200);
list.add(500);
// Returns the minimum element of the given collection, 
// according to the natural ordering of its elements.
// All elements in the collection must implement the Comparable interface.
System.out.println(Collections.min(list));

max(Collection extends?> coll)

根据元素的自然排序,返回给定集合中的最大元素。集合中的所有元素必须实现Comparable接口。 

此外,集合中的所有元素必须是相互可比的(也就是说,e1.compareTo(e2)不能对集合中的任何元素e1和e2抛出ClassCastException)。
例子。

List<Integer> list = new LinkedList<>();
list.add(100);
list.add(300);
list.add(200);
list.add(500);
//All elements in the collection must implement the Comparable interface. 
System.out.println(Collections.max(list));

相关文章