Here you can find the source of countDuplicates(Collection
static <T> List<Object> countDuplicates(Collection<T> items)
//package com.java2s; /*/* www .j ava2s.c o m*/ * Copyright (c) 2011 Google, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; public class Main { static <T> List<Object> countDuplicates(Collection<T> items) { // We use a List to de-dupe instead of a Set in case the elements don't have a proper // .hashCode() method (e.g., MessageSet from old versions of protobuf). List<T> itemSet = new ArrayList<T>(); for (T item : items) { if (!itemSet.contains(item)) { itemSet.add(item); } } Object[] params = new Object[itemSet.size()]; int n = 0; for (T item : itemSet) { int count = countOf(item, items); params[n++] = (count > 1) ? item + " [" + count + " copies]" : item; } return Arrays.asList(params); } static <T> int countOf(T t, Iterable<T> items) { int count = 0; for (T item : items) { if (t == null ? (item == null) : t.equals(item)) { count++; } } return count; } }