8

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.

James McMahon
  • 48,506
  • 64
  • 207
  • 283
john
  • 2,572
  • 11
  • 35
  • 51

3 Answers3

6

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 
sbglasius
  • 3,104
  • 20
  • 28
  • Even though I am not trying to do exactly what the OP is doing, this helped me out! Thanks! – djule5 Nov 03 '10 at 05:12
0

The subject of the question is somewhat general, so I'll post answer to a simplier question, if anyone got here looking for "How to merge two lists into a map in groovy?"

def keys = "key1\nkey2\nkey3"
def values = "value1,value2,value3"
keys = keys.split("\n")
values = values.split(",")
def map = [:]
keys.eachWithIndex() {param,i -> map[keys[i]] = values[i] }
print map
Noam Manos
  • 15,216
  • 3
  • 86
  • 85
0
import groovy.util.logging.Slf4j
import org.testng.annotations.Test

@Test
@Slf4j
class ExploreMergeListsOfMaps{
    final def listA = [[Name: 'mr good', note: 'good',rating:9], [Name: 'mr bad', note: 'bad',rating:5]]
    final def listB = [[Name: 'mr good', note: 'good',score:77], [Name: 'mr bad', note: 'bad', score:12]]

    void tryGroupBy() {
        def listIn = listA + listB
        def grouped = listIn.groupBy { item -> item.Name }
        def answer = grouped.inject([], { candidate, item -> candidate += mergeMapkeys( item.value )})
        log.debug(answer.dump())
    }

    private def mergeMapkeys( List maps ) {
        def ret =  maps.inject([:],{ mergedMap , map -> mergedMap << map })
        ret
    }
}
Bob Makowski
  • 305
  • 2
  • 8