【问题标题】:Remove elements by value satisfying certain condition按满足特定条件的值删除元素
【发布时间】:2015-10-14 19:58:17
【问题描述】:

从这些数据结构中,我想按值删除满足特定条件的元素

<Data Structures>

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

在previous question 中,我使用Collections.Singleton 找到了优雅的答案,但似乎需要完全匹配。

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

在这里,我想从表或地图中删除其值小于某个阈值的元素。你会用什么方式编写代码?


我刚查了两个答案,都是关于地图的答案,那桌案呢?我的解决方法如下。

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();
            }
        }
    }

【问题讨论】:

  • Table 完全没有什么不同。只需使用与地图相同的table.values()。您可以使用完全相同的代码。
  • @LouisWasserman 谢谢!刚刚签出的表工作完全相同。我试图以艰难的方式解决问题...... :(

标签: java dictionary data-structures


【解决方案1】:
Iterator<Integer> iterator = hmap.values().iterator();
while (iterator.hasNext()) {
  if (iterator.next() < threshold) {
     iterator.remove();
  }
}

当然,如果您使用的是 Java 8,那就容易多了:

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

表格的工作原理完全相同;只需使用table.values() 而不是hmap.values()。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-15
    • 2021-10-19
    • 1970-01-01
    • 2021-10-17
    相关资源
    最近更新 更多