【问题标题】:Remove those with a property not in a collection with commons-collections删除那些属性不在具有 commons-collections 的集合中的对象
【发布时间】:2012-01-02 23:14:47
【问题描述】:

假设我有一个foodGroupIds 的集合和一个food 的集合。使用 commons-collections,如何过滤掉不属于任何食物组的食物?

我可能在正确的轨道上,但无法弄清楚要使用什么谓词。也许必须创建我自己的?

Collection<Long> ids = collect(
    findGoodFoodGroups(),
    invokerTransformer("getId"));

Collection<Food> food = getAllFood();
filter(food, transformedPredicate(
    invokerTransformer("getFoodGroupId"),
    ?));

在 C# 中是这样的:

var ids = FindGoodFoodGroups().Select(x => x.Id);
var goodFood = FindAllFood().Select(x => ids.Contains(x.FoodGroupId));

我想要所有属性P 类型为T 的对象等于集合C 中的任何T 类型为T 的对象。

【问题讨论】:

    标签: java collections filtering apache-commons predicate


    【解决方案1】:

    我认为你可以使用Collection.removeAll(Collection)。

    简单例子:

        Map food = new HashMap();
        food.put("appleKey", "apple");
        food.put("orangeKey", "orange");
        food.put("tomatoKey", "tomato");
    
        Set unmatchedKeys = new HashSet(food.keySet());
        unmatchedKeys.removeAll(Arrays.asList("orangeKey"));
        System.err.println(unmatchedKeys);
    
        Collection unmatchedValues = new ArrayList(food.values());
        unmatchedValues.removeAll(Arrays.asList("apple", "tomato"));
        System.err.println(unmatchedValues);
    

    输出是:

    [appleKey, tomatoKey]
    [orange]
    

    【讨论】:

    • 嗯。对于字符串,如果您有一个任意数字的列表,然后想要删除那些长度不等于任何这些数字的字符串,那将更像是。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-17
    • 2016-11-28
    • 1970-01-01
    相关资源
    最近更新 更多