ssss
ssss

Reputation: 313

Simpler way to get duplicates from a list in groovy

Given the list:

list: [
   object1: {
     id: 22,
     name: "Tom"
   },
   object2: {
     id: 12,
     name: "Mary"
   },
   object3: {
     id: 44,
     name: "Tom"
   }
]

Instead of using nested loops, is there any other one-liner that would get ONLY duplicated names from this list ? So the return list would be ["Tom"]

Upvotes: 4

Views: 4610

Answers (2)

tim_yates
tim_yates

Reputation: 171084

Another way would be to group them with a count, and find all the ones where the count is greater than one:

list.name.countBy { it }.findResults { it.value > 1 ? it.key : null }

Or indeed as @Daniel says:

list.values().name.countBy { it }.findResults { it.value > 1 ? it.key : null }

Depending on your structure...

Upvotes: 2

Jacob Aae Mikkelsen
Jacob Aae Mikkelsen

Reputation: 579

Close to a oneliner is the below code. The idea is to create a list of unique named elements, and remove them from the original list.

def list = [
    [ id: 22, name: "Tom"],
    [ id: 12, name: "Mary"],
    [ id: 44, name: "Tom"]
]

def unique = list.toUnique { a, b -> a.name <=> b.name }
list.removeAll(unique)
list*.name

removeAll returns booleon, so that complicates it if you need 1 line of code, the unique variable can be foldet into the method call.

Notice, .toUnique() returns a new collection .unique() removes from the collection called on.

Upvotes: 1

Related Questions