Finding elements with same lastletter in a list

48 views Asked by At

I'm trying to figure out how I would use a closure which will find and groups of words that have the same ending letter.

For example: [United, Static, Rapid, Directed] The return should be ["D":3, "c":1]

1

There are 1 answers

3
injecteer On

If you want to group use:

def list = ['United', 'Static', 'Rapid', 'Directed']

def groupped = list.groupBy{ it[ -1 ] }
assert groupped == [d:['United', 'Rapid', 'Directed'], c:['Static']]

For counting only you can use:

def counted = list.inject( [:].withDefault{ 0 } ){ res, curr ->
  res[ curr[ -1 ] ]++
  res
}
assert counted == [d:3, c:1]