Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy merge two lists?

Tags:

merge

list

groovy

I have two lists:

listA: 
[[Name: mr good, note: good,rating:9], [Name: mr bad, note: bad, rating:5]] 

listB: 
[[Name: mr good, note: good,score:77], [Name: mr bad, note: bad, score:12]]

I want to get this one

listC:
[[Name: mr good, note: good,, rating:9, score:77], [Name: mr bad, note: bad, rating:5,score:12]] 

how could I do it ?

thanks.

like image 558
john Avatar asked Apr 08 '10 07:04

john


People also ask

How do I merge two lists in Groovy?

Combine lists using the plus operator The plus operator will return a new list containing all the elements of the two lists while and the addAll method appends the elements of the second list to the end of the first one. Obviously, the output is the same as the one using addAll method.

How to merge 2 maps in Groovy?

Merge maps using + operator The easiest way to merge two maps in Groovy is to use + operator. This method is straightforward - it creates a new map from the left-hand-side and right-hand-side maps.

How do I add a list to Groovy?

Groovy - add() Append the new value to the end of this List. This method has 2 different variants. boolean add(Object value) − Append the new value to the end of this List.


1 Answers

collect all elements in listA, and find the elementA equivilient in listB. Remove it from listB, and return the combined element.

If we say your structure is the above, I would probably do:

def listC = listA.collect( { elementA ->
    elementB = listB.find { it.Name == elementA.Name }

    // Remove matched element from listB
    listB.remove(elementB)
    // if elementB == null, I use safe reference and elvis-operator
    // This map is the next element in the collect
    [
        Name: it.Name,
        note: "${it.note} ${elementB?.note :? ''}", // Perhaps combine the two notes?
        rating: it.rating?:0 + elementB?.rating ?: 0, // Perhaps add the ratings?
        score: it.score?:0 + elementB?.score ?: 0 // Perhaps add the scores?
    ] // Combine elementA + elementB anyway you like
}

// Take unmatched elements in listB and add them to listC
listC += listB 
like image 179
sbglasius Avatar answered Nov 15 '22 01:11

sbglasius