2

Is there such a java Data Structure that can store unique elements and the count of any repeated elements?

For example say I have the given data : "a", "a", "a", "b", "b" , "c" , "d" I add each data element to this data structure and would get something similar to :

element : count a : 3 b : 2 c : 1 d : 1

Is there a java data structure that is already made to do something similar to this?

Rohan
  • 1,312
  • 3
  • 17
  • 43
  • 1
    No. But you could implement a `hashmap` and handle this. – TheLostMind Jul 16 '14 at 05:54
  • This link may help you http://stackoverflow.com/questions/15217438/map-for-counting-occurrences-of-the-key-in-java – Wundwin Born Jul 16 '14 at 06:02
  • Store Hashmap> where Entry keeps int and value. Wrap hashmap's method get(V) and put(K, V) and add getElementCount(V) method. – Ivan Ivanov Jul 16 '14 at 06:05
  • check http://www.mkyong.com/java/how-to-count-duplicated-items-in-java-list/ and http://stackoverflow.com/questions/11642151/how-to-get-the-number-of-repeated-valuescount-from-list – Jayesh Jul 16 '14 at 06:05

2 Answers2

4

Yes. Guava has a Multiset type you should use for this.

Multiset<String> bag = LinkedHashMultiset.create();
Collections.addAll(bag, "a", "a", "a", "b", "b", "c", "d");
for (Multiset.Entry<String> entry : bag.entrySet()) {
    System.out.println(entry.getElement() + " : " + entry.getCount());
}

Choose the right Multiset implementation depending on which iteration order you want:

  • For ordering by first insertion, use LinkedHashMultiset (as in my example above).
  • For ordering by natural order, or by a specific comparator, use TreeMultiset.
  • If you don't care about the order, use HashMultiset.

Obviously, these map to the same decisions you'd make for choosing a Map implementation.

C. K. Young
  • 219,335
  • 46
  • 382
  • 435
1

You can use a HashMap<String, Integer> to do what you want. And you can use it like so:

public class Test {
    public static void main(String[] args) {
        String[] data = new String[]{"a", "a", "a", "b", "b", "c", "d"};
        Map<String, Integer> map = new HashMap<String, Integer>();
        for(String d : data) {
            Integer value = map.get(d);
            if(value == null) {
                map.put(d, 1);
            }
            else {
                map.put(d, value + 1);
            }
        }
        System.out.println(map);
    }
}

Then it prints something like this:

{d=1, b=2, c=1, a=3}    
QBrute
  • 4,405
  • 6
  • 34
  • 40
  • The Guava Multiset approach is faster (and more semantically descriptive), so prefer that if you can use Guava. (Internally, it uses an internal `Count` class as the map value type, which is like a mutable `Integer`.) – C. K. Young Jul 16 '14 at 17:46