通过objid减去List

时间:2016-06-27 02:21:09

标签: groovy

我在Groovy中有这段代码:

def list1 = [[objid:1, name:"One"], [objid:2, name:"Two"]];
def list2 = [[objid:2, name:"Hello"]];
def list3 = list1 - list2;

println list3;

上面代码的输出结果如下:

[[objid:1, name:One], [objid:2, name:Two]]

问题:如何通过objid减去List?我希望结果是这样的:[[objid:1, name:One]]因为objid:2中存在List1。如何编码?

3 个答案:

答案 0 :(得分:2)

你可能需要一个功能,试试这个:

def list1 = [[objid:1, name:"One"], [objid:2, name:"Two"]];
def list2 = [[objid:2, name:"Hello"]];

​​def subtract (list1, list2) {
    def retlist = [];
    if (list1 == null || list2 == null) {
        return null;
    }

    for(test1 in list1) {
        def exists = false;
        for (test2 in list2) {
            exists = (test1.objid == test2.objid) || exists;
        }
        if (!exists) {
            retlist.push(test1);
        }
    }
    return retlist;
}

def list3 = subtract(list1 ,list2)​​;

println list3;​

答案 1 :(得分:2)

鉴于

list1 = [[objid:1, name:"One"], [objid:2, name:"Two"]]
list2 = [[objid:2, name:"Hello"]]

为了获得list1条目,其中包含与list2中的objids匹配的条目,请将需要减去的id收集到一个集合中,然后构造一个谓词,测试给定对象的id不在其中设置:

ids = list2.collect { it['objid'] } as Set
list3 = list1.findAll { !ids.contains(it['objid']) }

(使用集合代替列表可以使查找更快。)

结果是list3包含:

[[objid:1, name:One]]

答案 2 :(得分:1)

您需要一个执行以下操作的功能:

SELECT
    DAY( -- Day part
        DATEADD(DAY, -1, -- Last day of the month
            DATEADD(MONTH, CAST(LEFT(@input, 2) AS INT), -- Start of next month
                DATEADD(YEAR, CAST(RIGHT(@input, 4) AS INT) - 1900, 0) -- Start of the year
            )
        )
    )