-1

i am have problem. Actually i am working on some code and that code is written in python but i want to do same problem in java .i got everything but on collection some problem is coming.

i am storing values in dictionary in java :

 Dictionary<String, Integer> dc=new Hashtable<String, Integer>();
  String s[]={"red", "blue", "red", "green", "blue", "blue"};
    for(String t: s){

        if(dc.get(t)==null)

           dc.put(t, 1);
    else
            dc.put(t, dc.get(t)+1);
}

output:

{blue=3, green=1, red=2}

i want like:

{blue=3, red=2, green=1}

but this is not the output i want i want like python gave:

cnt = Counter()
>>> for word in ['red', 'blue', 'red', 'green', 'blue', 'blue']:
...     cnt[word] += 1
>>> cnt
Counter({'blue': 3, 'red': 2, 'green': 1})

can any one give me some idea ?

Rahul Kulhari
  • 1,115
  • 1
  • 15
  • 44

1 Answers1

2

Don't use a HashTable, this is one of the obsoleted collections.

I'm not sure on the order you want to maintain but there are numerous different Map types. A HashTable is equivalent to a HashMap but is is syncronized is a slightly non-useful manner.

Lets go through the options:

final Map<String, Integer> m = new HashMap<>()

This will create a HashMap which, like a HashTable, provides no guarantees about the order of iteration.

final Map<String, Integer> m = new LinkedHashMap<>()

A LinkedHashMap is similar to a HashMap except for the fact that it maintains a doubly linked list of the elements so that the iteration order of the elements is the insertion order.

final Map<String, Integer> m = new TreeMap<>()

A TreeMap is a very different beast to both hash based maps. The TreeMap stores its elements in a Tree providing O(1) lookups and O(lg n) puts - it is therefore slower. However, the TreeMap keeps all of its elements sorted at all times. The default constructor sorts elements by their natural order, so elements must implements Comparable and the TreeMap will use that to sort the elements.

Given that you are trying to use a Dictionary and a HashTable, both of which were obsoleted by the release of Java 1.2 in 1998 I would suggest that you read about the Java Collections API, specifically about Maps but reading the whole lot won't hurt.

Boris the Spider
  • 59,842
  • 6
  • 106
  • 166