Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove elements by value satisfying certain condition

From these data structures, I want to remove elements by value, that satisfies certain condition

<Data Structures>

 - RowSortedTable<String, String, Double> a;     (Guava Table)
 - HashMap<String, Double> b;

From the previous question, I found the elegant answer using Collections.Singleton however, it seems like exact matching is required.

hmap.values().removeAll(Collections.singleton("Two"));

Here, I want to remove elements from a table or map where their values are smaller than certain threshold. What would be your way to write the code?


I just checked two answers and those are answers about map, how about the table case? My solution is as follows.

for (Iterator<String> it1 = proptypeconf.columnKeySet().iterator(); it1.hasNext();) {
        String type = it1.next();
        System.out.println(type);
        for (Iterator<Map.Entry<String, Double>> it2 = proptypeconf.column(type).entrySet().iterator(); it2.hasNext();){
            Map.Entry<String, Double> e = it2.next();
            if (e.getValue() < conflist.get(index-1)) {
                it2.remove();
            }
        }
    }
like image 373
SUNDONG Avatar asked Oct 14 '15 19:10

SUNDONG


1 Answers

Iterator<Integer> iterator = hmap.values().iterator();
while (iterator.hasNext()) {
  if (iterator.next() < threshold) {
     iterator.remove();
  }
}

Of course, if you're on Java 8, it's much easier:

hmap.values().removeIf(value -> value < threshold);

Tables work exactly the same; just use table.values() instead of hmap.values().

like image 91
Louis Wasserman Avatar answered Sep 19 '22 22:09

Louis Wasserman