使用Collections.frequency检查Java中元素的频率

用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