Count the number of occurrences in a given collection. - Java java.util

Java examples for java.util:Collection Operation

Description

Count the number of occurrences in a given collection.

Demo Code

/*/*from   w w  w .j  a  v a 2s. c  o m*/
   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/>.
 */
//package com.java2s;

import java.util.Collection;
import java.util.HashMap;

import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

public class Main {
    public static void main(String[] argv) {
        Collection collection = java.util.Arrays.asList("asdf",
                "java2s.com");
        System.out.println(countOccurrences(collection));
    }

    /**
     * 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 Tutorials