How to Count Items in a List in Java


In this example we will show how to count entries in a list using Collections.frequency().

Source Code

package com.beginner.examples;

import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.ArrayList;
import java.util.Set;

public class CountDuplicatedList {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		List aList = new ArrayList();
		aList.add("a");
		aList.add("b");
		aList.add("a");
		aList.add("b");
		Set set = new HashSet(aList);
		for (String str : set) {
			System.out.println(str + ":" + Collections.frequency(aList, str));
		}
	}
}

Output:

b 2
a 2

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments