java frequency_Java Java.util.Collections.frequency()用法及代码示例

java.util.Collections类中提供了java.util.Collections.frequency()方法。它用于获取出现在指定Collection列表中的元素的频率。更正式地说,它返回集合中元素e的数量。

用法

public static int frequency(Collection> c, Object o)

参数:

c - the collection in which to determine the frequency of o

o - the object whose frequency is to be determined

返回:

Returns the number of elements in the specified collection

equal to the specified object.

Throws:

NullPointerException - if c is null

// Java program to demonstrate working of

// java.utils.Collections.frequency()

import java.util.*;

public class FrequencyDemo

{

public static void main(String[] args)

{

// Let us create a list of strings

List  mylist = new ArrayList();

mylist.add("practice");

mylist.add("code");

mylist.add("code");

mylist.add("quiz");

mylist.add("geeksforgeeks");

// Here we are using frequency() method

// to get  frequency of element "code"

int freq = Collections.frequency(mylist, "code");

System.out.println(freq);

}

}

输出:

2

How to Quickly get frequency of an element in an array in Java ?

Java中的数组类没有频率方法。但是我们也可以使用Collections.frequency()来获取数组中元素的频率。

// Java program to get frequency of an element

//  with java.utils.Collections.frequency()

import java.util.*;

public class FrequencyDemo

{

public static void main(String[] args)

{

// Let us create an array of integers

Integer arr[] = {10, 20, 20, 30, 20, 40, 50};

// Please refer below post for details of asList()

// https://www.geeksforgeeks.org/array-class-in-java/

int freq = Collections.frequency(Arrays.asList(arr), 20);

System.out.println(freq);

}

}

输出:

3

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值