Reputation: 793
I have this code in Groovy
:
def list1 = [[objid:1, name:"One"], [objid:2, name:"Two"]];
def list2 = [[objid:2, name:"Hello"]];
def list3 = list1 - list2;
println list3;
The output of the code above will result something like this:
[[objid:1, name:One], [objid:2, name:Two]]
QUESTION: How to subtract List
by objid? I want the result to be something like this: [[objid:1, name:One]]
since objid:2
is present in the List1
. How to code it?
Upvotes: 1
Views: 102
Reputation: 12378
You may need a function, try this:
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;
Upvotes: 2
Reputation: 96394
Given
list1 = [[objid:1, name:"One"], [objid:2, name:"Two"]]
list2 = [[objid:2, name:"Hello"]]
In order to get list1 entries with entries matching objids from list2 filtered out, collect the ids that need to be subtracted into a set, then construct a predicate that tests that the id of the given object isn't in that set:
ids = list2.collect { it['objid'] } as Set
list3 = list1.findAll { !ids.contains(it['objid']) }
(Using a set instead of a list should make the lookups faster.)
The result is that list3 contains:
[[objid:1, name:One]]
Upvotes: 2
Reputation: 27214
You'll want a function that does the following:
class Foo
{
public String Name;
public Integer Id;
}
public Foo getObjId(int id) {
for (Foo foo : list) {
if (foo.getId() == id) {
return foo; // foo bar!
}
}
return null; // foo bar not found.
}
Upvotes: 1