1

My program is a very simple one. All I need to do is track the duplicates and print the unique and the duplicate elements separately. I am using a hashmap for this. (dup is an arraylist containing all the elements)

    Map<Employee, Integer> newMap = new HashMap();
    int count = 0;
    for (Employee element : dup) {

        System.out.println("oooo" + element);
        if (newMap.put((Employee) element, count) != null) {
            newMap.put((Employee) element, newMap.get(element) + 1);
        }
    }
    System.out.println("oooo" + newMap);

The o/p generated is:

    Employee No :9 Employee Name :Swasti Employee MailId :swasti@gmail.com=0, Employee No :2 Employee Name :Shanthi Employee MailId :shanthi@gmail.com=0

The records with duplicates are incremented and the o/p is :

    Employee Name :Shreya Employee MailId :shreya@gmail.com=1, Employee Name :Sujatha Employee MailId :suravich@gmail.com=1

The problem here is that the count is not incrementing more than one for records with more number of duplicates. I don't understand why. Any sort of help on this would be appreciated.

P.S: I tried doing this with an arraylist and a hashset and did get an output but using a map seemed like a better way.

suravich
  • 13
  • 1
  • 4

3 Answers3

1

This is because with this line:

if (newMap.put((Employee) element, count) != null) {

you put 0 again each time (since count is always 0 in your code). And on the next line, your newMap.get(element) will therefore be 0...

You need to grab the old value and check that it is not null:

Integer oldValue = newMap.put((Employee) element, 0);
if (oldValue != null)
    newMap.put((Employee) element, oldValue + 1);

Note that your dup should be a List<Employee>, not a raw List. This would avoid all the casts you have to make currently.

fge
  • 119,121
  • 33
  • 254
  • 329
0
        if (newMap.containsKey(element)) {
            newMap.put(element, newMap.get(element) + 1);
        }

Also since you using generics you need to typecast.

Aniket Thakur
  • 66,731
  • 38
  • 279
  • 289
0
if (newMap.get(element) != null) {
    newMap.put(element, newMap.get(element) + 1);
} else {
    newMap.put(element, 1);
}
DmitryKanunnikoff
  • 2,226
  • 2
  • 22
  • 35