2

I have a HashMap with float values.

HashMap<Integer,Float> map : {(1,0.0),(2,0.0),(3,2000.0),(4,3000.0)}

I want to remove all the entries in it with zero values. The result should be:

 map : {(3,2000.0),(4,3000.0)}

Update: I'm using Java 7

Sandeep Yohans
  • 929
  • 1
  • 14
  • 36

3 Answers3

6

As of Java 8 you can simply use

map.values().removeIf(f -> f == 0f);

According to the JavaDoc this will remove all of the elements of map that satisfy the given predicate.

EDIT
As you updated your question, that you are using Java 7 use an Iterator on the values():

Iterator<Float> iterator = map.values().iterator();
while (iterator.hasNext()) {
    if (iterator.next() == 0f) {
        iterator.remove();
    }
}

This works because according to the JavaDoc map.values()

Returns a Collection view of the values contained in this map. The collection is backed by the map, so changes to the map are reflected in the collection, and vice-versa.

LuCio
  • 5,055
  • 2
  • 18
  • 34
0
for (Iterator<Map.Entry<Integer,Float>> it = map.entrySet().iterator(); 
 it.hasNext();) 
 {
     Map.Entry<Integer, Float> entry = it.next();
     if (entry.getValue() == 0.0) {
        it.remove();
     }
   }
Sandeep Yohans
  • 929
  • 1
  • 14
  • 36
0

Pay attention on compare not integer values. double and float should not be compared with ==. This should be a rule, because this is precise vlue, and == 0 should menas smth. like -10E-12 <= float <= 10E-12 (delta range).

// Java 7
Iterator<Float> it = map.values().iterator();

while (it.hasNext()) {
    if (it.next().compareTo(0f) == 0)
        it.remove();
}

// Java 8
map.values().removeIf(value -> Float.compare(value, 0) == 0);
Oleg Cherednik
  • 17,377
  • 4
  • 21
  • 35