Is there a way determine how many times an Object occurs within a Collection?
Created May 8, 2012
Brandon Rohlfs
The Collections class provides a method which returns the number of times an Object appears within a given Collection.
public static int frequency(Collection<?> c, Object o)If a null Collection is passed in then a NullPointerException is thrown.
import java.util.*; public class Freq { public static void main(String[] args){ List<Integer> password = new ArrayList<Integer>(); password.add(new Integer(4)); password.add(new Integer(6)); password.add(new Integer(8)); password.add(new Integer(4)); password.add(new Integer(9)); Integer passwordelement = new Integer(4); System.out.println(passwordelement + " appears " + getFrequency(password,passwordelement) + " times within password"); } private static int getFrequency(Collection c, Object o){ return(Collections.frequency(c,o)); } }