Here you can find the source of countOccurrences(final Collection
Parameter | Description |
---|---|
T | the type to count the occurrences in the given collection for |
collection | the targeted collection to count repeated instances in |
public static <T> Map<T, AtomicInteger> countOccurrences(final Collection<T> collection)
//package com.java2s; /*/*from w ww . ja v a2 s. com*/ Copyright (C) 2016 HermeneutiX.org This file is part of SciToS. SciToS is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SciToS is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with SciToS. If not, see <http://www.gnu.org/licenses/>. */ import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; public class Main { /** * Count the number of occurrences in a given collection. * * @param <T> * the type to count the occurrences in the given {@code collection} for * @param collection * the targeted collection to count repeated instances in * @return mapping of contained instances to their respective count of occurrences */ public static <T> Map<T, AtomicInteger> countOccurrences(final Collection<T> collection) { final Map<T, AtomicInteger> map = new HashMap<T, AtomicInteger>(); for (final T instance : collection) { final AtomicInteger counter = map.get(instance); if (counter == null) { map.put(instance, new AtomicInteger(1)); } else { counter.incrementAndGet(); } } return map; } }