Collections.frequency(Collection, Object): This method is available in java.util.Collections class of Java.
Syntax:
int java.util.Collections.frequency(Collection<?> c, Object o)
This method takes two arguments. This method returns the number of elements in the specified collection equal to the specified object.
Parameters: Two parameters are required for this method.
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 c equal to o.
Throws:
NullPointerException - if c is null.
Approach 1: When no exception
Java
import java.util.ArrayList;import java.util.Collections;import java.util.List;public class Collectionsfrequency {public static void main(String[] args) {List<Integer> arrlist = new ArrayList<Integer>();arrlist.add(12);arrlist.add(10);arrlist.add(10);arrlist.add(11);arrlist.add(10);System.out.println(Collections.frequency(arrlist, 10));}}
Output:
3
Approach 2: NullPointerException
Java
import java.util.Collections;import java.util.List;public class Collectionsfrequency {public static void main(String[] args) {List<Integer> arrlist = null;System.out.println(Collections.frequency(arrlist, 10));}}
Output:
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.util.Collection.iterator()" because "c" is null at java.base/java.util.Collections.frequency(Collections.java:5465)
No comments:
Post a Comment