Java Collections類的frequency()方法用於獲取指定集合中與指定對象相等的元素個數。
用法
以下是 frequency() 方法的聲明:
public static int frequency(Collections<?> c, Object obj)
參數
參數 | 描述 | 必需/可選 |
---|---|---|
c | 它是確定 obj 出現頻率的集合。 | Required |
obj | 它是要確定其頻率的對象。 | Required |
返回
frequency() 方法返回集合 c 中等於指定對象 obj 的元素數。
異常
NullPointerException - 如果集合 c 為空,則會拋出此異常。
兼容版本
Java 1.5 及以上
例子1
import java.util.*;
public class CollectionsFrequencyExample1 {
public static void main(String[] args) {
//Create a list object
List<String> arrlist = new ArrayList<String>();
//Add elements in the list
arrlist.add("Java");
arrlist.add("COBOL");
arrlist.add("Java");
arrlist.add("C++");
arrlist.add("Java");
System.out.println("List of elements:"+arrlist);
//Count the frequency of the given word
System.out.println("Frequency of the Word:"+Collections.frequency(arrlist,"Java"));
}
}
輸出:
List of elements:[Java, COBOL, Java, C++, Java] Frequency of the Word:3
例子2
import java.util.*;
public class CollectionsFrequencyExample2 {
public static void main(String[] args) {
//Create a list object
List<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(1);
list.add(3);
list.add(2);
list.add(3);
list.add(4);
System.out.println("List of elements:"+list);
System.out.println("\nCount all with frequency:");
Set<Integer> uniqueSet = new HashSet<Integer>(list);
for (Integer i:uniqueSet) {
System.out.println(i + ":" + Collections.frequency(list, i));
}
}
}
輸出:
List of elements:[1, 2, 1, 3, 2, 3, 4] Count all with frequency: 1:2 2:2 3:2 4:1
例子3
import java.util.*;
public class CollectionsFrequencyExample3 {
public static void main(String[] args) {
// Let us create an array of integers
Integer arr[] = {20, 10, 20, 30, 20, 40, 20};
int freq = Collections.frequency(Arrays.asList(arr), 20);
System.out.println("Frequency of 20 is:"+freq);
}
}
輸出:
Frequency of 20 is:4
相關用法
- Java Collections frequency()用法及代碼示例
- Java Collections fill()用法及代碼示例
- Java Collections synchronizedSortedSet()用法及代碼示例
- Java Collections checkedQueue()用法及代碼示例
- Java Collections unmodifiableNavigableSet()用法及代碼示例
- Java Collections checkedSet()用法及代碼示例
- Java Collections copy()用法及代碼示例
- Java Collections checkedMap()用法及代碼示例
- Java Collections synchronizedNavigableSet()用法及代碼示例
- Java Collections singleton()用法及代碼示例
- Java Collections nCopies()用法及代碼示例
- Java Collections emptySet()用法及代碼示例
- Java Collections newSetFromMap()用法及代碼示例
- Java Collections checkedSortedMap()用法及代碼示例
- Java Collections addAll()用法及代碼示例
- Java Collections sort()用法及代碼示例
- Java Collections emptySortedSet()用法及代碼示例
- Java Collections max()用法及代碼示例
- Java Collections checkedSortedSet()用法及代碼示例
- Java Collections checkedCollection()用法及代碼示例
注:本文由純淨天空篩選整理自 Java Collections frequency() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。