使用 Collections.frequency 检查 Java 中元素的频率
java 8object oriented programmingprogramming
在 Java 中创建列表 −
List< String >list = Arrays.asList("P","Q","R","P","T","P","U","V","W","X","W" );
现在,假设您想要获取元素 P 的频率。为此,请使用 Collections.frequency() 方法 −
Collections.frequency(list, "P");
如上所示,我们也可以找到任何字母的出现 −
Collections.frequency(list, "T");
示例
import java.util.Arrays; import java.util.Collections; import java.util.List; public class Demo { public static void main(String[] args) { List<String>list = Arrays.asList("P","Q","R","P","T","P","U","V","W","X","W" ); int checkOccurrence = Collections.frequency(list, "P"); System.out.println("Occurrence of P = " + checkOccurrence); checkOccurrence = Collections.frequency(list, "W"); System.out.println("Occurrence of W = " + checkOccurrence); checkOccurrence = Collections.frequency(list, "T"); System.out.println("Occurrence of T = " + checkOccurrence); } }
输出
Occurrence of P = 3 Occurrence of W = 2 Occurrence of T = 1