检查 Java 中元素的频率,带有 Collections.frequency
在 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
广告