Java Collections frequency()
frequency() 可以统计出某个对象在Collection中出现的次数。
1 语法
public static int frequency(Collections<?> c, Object obj)
2 参数
c:需要查询的集合。
obj:要查询出现频率的对象。
3 返回值
返回对象出现频率数。
4 Collections frequency()示例1
package com.yiidian;
/**
* 一点教程网: http://www.yiidian.com
*/
/**
* Java Collections.frequency的例子
*/
import java.util.*;
public class Demo {
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
5 Collections frequency()示例2
package com.yiidian;
/**
* 一点教程网: http://www.yiidian.com
*/
/**
* Java Collections.frequency的例子
*/
import java.util.*;
public class Demo {
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
6 Collections frequency()示例3
package com.yiidian;
/**
* 一点教程网: http://www.yiidian.com
*/
/**
* Java Collections.frequency的例子
*/
import java.util.*;
public class Demo {
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
热门文章
优秀文章