Description

Returns a map where each entry represents the number of times that the corresponding key appears in the input collection.

License

Open Source License

Parameter

Parameter Description
A Key type
collection Input collection

Return

Map where the key is an item appearing in the input collection, and the value is the number of times that appears

Declaration

public static <A> Map<A, Integer> count(Collection<A> collection) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2016 Pablo Pavon-Marino.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Lesser Public License v2.1
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/lgpl.html
 *
 * Contributors:/*from  w  ww  . j av a2  s  .  co  m*/
 *     Pablo Pavon-Marino - Jose-Luis Izquierdo-Zaragoza, up to version 0.3.1
 *     Pablo Pavon-Marino - from version 0.4.0 onwards
 ******************************************************************************/

import java.util.*;

public class Main {
    /**
     * Returns a map where each entry represents the number of times that the
     * corresponding key appears in the input collection.
     *
     * @param <A> Key type
     * @param collection Input collection
     * @return Map where the key is an item appearing in the input collection, and the value is the number of times that appears
     */
    public static <A> Map<A, Integer> count(Collection<A> collection) {
        Map<A, Integer> out = new LinkedHashMap<A, Integer>();
        for (A value : collection)
            out.put(value, out.containsKey(value) ? out.get(value) + 1 : 1);

        return out;
    }
}

Related

  1. count(Collection collection)
  2. count(Collection ts, T toCount)
  3. count(final Collection collection, final ItemType item)
  4. count(final Collection blocks)
  5. count(T x0, T x1, T x2, Collection sentences)