Natasha
Natasha

Reputation: 35

Which is the best Java Data structure for my application?

My problem statement is like that when i get a data , i store it in a data structure and keep a counter.If something similar comes then by searching it in the data structure if similar thing is already present there then just increment the counter and there is no limit of my data. The data can be sometimes very larger.So being a beginner in java i want to know which data structure would be good/efficient for my problem.

Upvotes: 1

Views: 299

Answers (2)

Eve Freeman
Eve Freeman

Reputation: 33155

You want a HashMap, with whatever your "data" as the key, and a counter as the value.

http://docs.oracle.com/javase/1.4.2/docs/api/java/util/HashMap.html

The reason it's a good choice is because it has O(1) "contains" checking, retrieval, and insertion time. As long as you don't need to sort your data, it's an excellent choice.

This untested code should get you started. Replace String with the type of your data. If it's a custom class, you must overload hashCode() and equals().

HashMap<String, Integer> map = new HashMap<String, Integer>();

...

Integer i = map.get(data);
if(i == null) {
   map.put(data, 1);
} else {
   map.put(data, i + 1);
}

Upvotes: 3

Petar Ivanov
Petar Ivanov

Reputation: 93030

Sound like you need to use a HashMap<YourClass, Integer> (link).

The value is the counter, that's why it is integer. when something comes you check to see if an item with that key exists. If not you add it (with a value of 1), otherwise you add it with a value of one plus the previous value.

You can optimize on that by instead of Integer make your value be a custom class, which wraps an integer and allows to be incremented. This way you won't have to insert into the hash map every time when you increment.

Upvotes: 1

Related Questions