1

I want to remove keys from map in case if the value for the key is zero(0) i am able to achieve it using
map.values().removeAll(Collections.singleton(0l));

.
It was working nice till i was using Map<String,Long> but now we have changed the implementation to Map<String,AtomicLong> now it dosen't remove the keys whose values are zero since i am using an Atomic variable as value.
Small code snippet on which i tried ::

    Map<String, AtomicLong> atomicMap = new HashMap<String,AtomicLong>();
    atomicMap.put("Ron", new AtomicLong(0l));
    atomicMap.put("David", new AtomicLong(0l));
    atomicMap.put("Fredrick", new AtomicLong(0l));
    atomicMap.put("Gema", new AtomicLong(1l));
    atomicMap.put("Andrew", new AtomicLong(1l));    

    atomicMap.values().removeAll(Collections.singleton(new AtomicLong(0l)));

    System.out.println(atomicMap.toString());

which outputs as
{Ron=0, Fredrick=0, Gema=1, Andrew=1, David=0}

as you can see the keys which have values 0 are not being removed. Can anyone suggest a solution over this , it will be of great help.
Thanks.

Anand Kadhi
  • 1,790
  • 4
  • 27
  • 40

3 Answers3

2

If you are using Java8, there is a removeIf method that you could use.

atomicMap.values().removeIf(x -> x.get() == 0L);
// Prints {Gema=1, Andrew=1}
Todd
  • 30,472
  • 11
  • 81
  • 89
1

Two instances of AtomicLong are never equal. If you look at AtomicLong you can see that it never overrides the equal() method. See Why are two AtomicIntegers never equal?

You can overcome this with your own custom AtomicLong implementation, which implements equals() and make your strategy to remove the elements work.

public class MyAtomicLongExample {

    static class MyAtomicLong extends AtomicLong {

        private static final long serialVersionUID = -8694980851332228839L;

        public MyAtomicLong(long initialValue) {
            super(initialValue);
        }

        @Override
        public boolean equals(Object obj) {
            return obj instanceof MyAtomicLong && ((MyAtomicLong) obj).get() == get();
        }
    }

    public static void main(String[] args) {
        Map<String, MyAtomicLong> atomicMap = new HashMap<>();
        atomicMap.put("Ron", new MyAtomicLong(0l));
        atomicMap.put("David", new MyAtomicLong(0l));
        atomicMap.put("Fredrick", new MyAtomicLong(0l));
        atomicMap.put("Gema", new MyAtomicLong(1l));
        atomicMap.put("Andrew", new MyAtomicLong(1l));    

        atomicMap.values().removeAll(Collections.singleton(new MyAtomicLong(0l)));

        System.out.println(atomicMap);
    }

}

This will print {Gema=1, Andrew=1}

Community
  • 1
  • 1
Fred Porciúncula
  • 8,533
  • 3
  • 40
  • 57
1

Incase if you want to compute then decide to remove when value is zero.

if (atomicMap.compute("Andrew", (k, v) ->  v.decrementAndGet()) == 0) {

      atomicMap.remove("Andrew");
}
Kanagavelu Sugumar
  • 18,766
  • 20
  • 94
  • 101