No Duplicates in Collection
For the collection that should have no duplicate Items, use a Set<Item>
instead of an ArrayList<Item>
. The Set
data structure will not store duplicates. Since Item
is a custom object you created, you will need to override the hashCode
and equals
method in your Item
class.
This approach is O(1) - which is way better than keep an ArrayList<Item>
and iterating it and searching for a duplicate (which will be O(n) at worst).
Occurrences
For the occurrences problem, instead of keeping your items in an ArrayList<Item>
, keep them in a Map<Item,Integer>
. This will map the item to how many occurrences there are of it.
Using the map, you will need to get the key, which is the Item
you are about to add. If it already exists in the map, simply add one to the value of that key (the occurrences number).
If they key doesn't exist yet (this is the first time this Item
will be inserted into the map), simply add it to the map, and set the value as 1.
Using a map will also be a way more efficient solution, as it will also be O(1), instead of O(n) if an ArrayList<Item>
will be used.
Example:
Set<Item> itemSet = new HashSet<>();
Map<Item,Integer> occurencesMap = new HashMap<>();
itemSet.add(yourItem);
itemSet.add(yourItem);
itemSet.add(secondItem);
//itemSet now contains only 2 objects!
if (occurencesMap.get(yourItem) == null){
occurencesMap.put(yourItem,1);
}
else{
//adding 1 to the current value of occurences for that item.
occurencesMap.get(yourItem)++;
}