Java AtomicInteger countOccurrences(final Collection collection)

Here you can find the source of countOccurrences(final Collection collection)

Description

Count the number of occurrences in a given collection.

License

Open Source License

Parameter

Parameter Description
T the type to count the occurrences in the given collection for
collection the targeted collection to count repeated instances in

Return

mapping of contained instances to their respective count of occurrences

Declaration

public static <T> Map<T, AtomicInteger> countOccurrences(final Collection<T> collection) 

Method Source Code

//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;
    }
}

Related

  1. addNodeUse(String nodeInfo)
  2. bitwiseOrAndGet(final AtomicInteger ai, final int toOrValue)
  3. count()
  4. count(byte[] array, byte value)
  5. countDownToZero(AtomicInteger counter)
  6. create()
  7. createIdentifier(Class clazz)
  8. createNewTestNamespace( Map environmentProperties)
  9. createThreadFactory(final String prefix)