adp7
adp7

Reputation: 68

Merging list sharing a key in Groovy

I'm new to Groovy and I'm trying to merge lists sharing a key, the ouput must be key, sub-list1, sub-list2 ...

["08_087C", 1 , 225]
["08_087C", 0 , 179]
// Out
["08_087C", [0 , 179], [1 , 225]]

The order of the sub-lists doesn't matter.

What would be the right way to do this, without "reinventing the wheel" ?

Upvotes: 0

Views: 197

Answers (3)

Prakash Thete
Prakash Thete

Reputation: 3892

You can just use the intersection property on list as below

List firstList = ​["08_087C", 1 , 225]
List secondList = ["08_087C", 0 , 179] 

//check if they have common element
def intersectElement = secondList.intersect(firstList) ? secondList.intersect(firstList)[0] : null
if(intersectElement){

    //build the final list
    List outputList = [intersectElement, firstList.minus(intersectElement),secondList.minus(intersectElement)] 
    println "outputList : " + outputList
}

Output:

outputList : ["08_087C", [1, 225], [0, 179]]

Upvotes: 0

cfrick
cfrick

Reputation: 37063

If you are talking about "keys" in the context of a list, your result most likely should be a Map, which makes later handling alot easier, if you want to access your data by said key. The following code, does exactly as you asked for.

It groups your rows by the first element and puts them in a single row on that key. Since your example is sorted, but you failed to mention, your constraints there, I assume you can live with the default sort order.

def data = [
    ["08_087C", 1, 225],
    ["08_087C", 0, 179],
]

assert data.groupBy{ 
    it.head() 
}.collect{ k, v -> 
    [k] + v*.tail().sort()
} == [["08_087C", [0, 179], [1, 225],]]

And here is the same code to create a Map instead. The differences is the use of collectEntries instead of collect:

assert data.groupBy{ 
    it.head() 
}.collectEntries{ k, v -> 
    [k, v*.tail().sort()]
} == ["08_087C": [[0, 179], [1, 225],]]

Upvotes: 1

sfgroups
sfgroups

Reputation: 19133

see this helps

def l1 = ["08_087C", 1 , 225]
def l2 =["08_087C", 0 , 179]
def out= [l1.intersect(l2), [l1.minus(l2)],[l2.minus(l1)]]
println out

Upvotes: 0

Related Questions