Java Collections frequency()
Java Collections 类的
frequency()方法用于获取指定集合中等于的元素数到指定对象。
语法
以下是
frequency()方法的声明:
public static int frequency(Collections<?> c, Object obj)
参数
参数 |
说明 |
必需/可选 |
c |
它是确定obj频率的集合。 |
必需 |
obj |
是要确定其频率的对象。 |
必需 |
返回
frequency()方法返回集合c中等于指定对象obj的元素数。
异常
NullPointerException -如果集合c为null,则将引发此异常。
兼容性版本
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);
}
}
输出: