按值满足某些条件删除元素 [英] Remove elements by value satisfying certain condition

查看:124
本文介绍了按值满足某些条件删除元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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;

来自上一个问题,我找到了优雅的答案使用 Collections.Singleton 然而,似乎需要完全匹配。

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


推荐答案

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

当然,如果你使用的是Java 8,它更容易:

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

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

表的工作方式完全相同;只需使用 table.values()而不是 hmap.values()

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

这篇关于按值满足某些条件删除元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆