Java - getting the number of types in a list

I have a list. A list may contain several elements of the same type of enumeration.

Suppose that I have a transfer: TOYthat matter: BALL, DOLL, PLAYSTATION. I want to know how many items PLAYSTATIONare in a list with a type TOY. (i.e. toys List<Toy>)

What is the best possible solution for this? I do not want to constantly iterate over the list in the list.

+3
source share
8 answers

You can use Apocal commons-collections ' HashBag. It has a method getCount(Object)that suits you.

+8

java.util.Collections frequency(Collection c, Object type).

:

int amountOfPlayStations = Collections.frequency(toys, TOY.PLAYSTATION);
+2

, , , / . , , , .

, , add/remove/addAll , . , .

+1

, , :

public int count(List<Toy> haystack, Toy needle) {
    int result;
    for (Toy t : haystack) {
        if (t == needle) {
           result++;
        }
    }
    return result;
}

PLAYSTATION . , , , Map<Toy, Integer> .

+1

, ForwardingList . HashBag :

  • List, , List

, , , .

, . : , , / , :

import com.google.common.collect.ForwardingList;


public class CountingList<E> extends ForwardingList<E> {

    private List<E> backingList = new LinkedList<E>();
    private Map<E, Integer> countMap = new HashMap<E, Integer>();

    @Override
    protected List<E> delegate() {
        return backingList;
    }

    @Override
    public boolean add(E element) {
        backingList.add(element);
        if(countMap.containsKey(element)) {
            countMap.put(element, countMap.get(element) + 1);
        } else {
            countMap.put(element, 1);
        }
        return true;
    }

    public int getCount(E element) {
        Integer count = countMap.get(element);
        return count != null ? count.intValue() : 0;
    }

}
+1

java.util.List , .. , , , . java.util.Map, . , .

0

HashBag (by Bozho), , . Googles Collections 2 :

List<Toy> toys;
List<Toy> playstations = Collections2.filter( toys, new Predicate() {
  boolean apply(TOY toy){
    return toy == TOY.PLAYSTATION;
  }
});
0

( Collections.Frequency), google, [Collections2.transform] [2], .

[2]: http://google-collections.googlecode.com/svn/trunk/javadoc/com/google/common/collect/Collections2.html#transform(java.util.Collection, com.google.common.base.Function)

0

Source: https://habr.com/ru/post/1724958/


All Articles