Home > Net >  Groovy: group trades by portfolio with string search
Groovy: group trades by portfolio with string search

Time:12-16

I'm not programmer but I need your help because I was left with IT system with no IT support, so I need to change code by myself. So sorry for stupid question, your help will be highly appreciated, i hope it is not too difficult... I have code

trades.groupBy {
  data.findRecord('Portfolios', it.portfolioId).getFieldValue('Name').toString().substring(0,4) 
} 

which takes first 4 symbols of portfolio name and groups trades. I need new rule:

  1. if name contains | sign, find number of this sign in the string (n) and take n-2 first signs
  2. if name doesn't contain | take all signs of this string.

For example I have portfolio names

14717_81   
14717_81 | John  
14717_78 | Jane  

So first two trades will be grouped

CodePudding user response:

The main idea of my solution is pretty simple.

I use split() on each "trade", take the 1st part of it and make the list unique:

def trades = '''\
14717_81
14717_81 | John
14717_78 | Jane'''.readLines()

trades = trades*.split( /\s*\|\s*/ )*.first().unique()

assert trades == ['14717_81', '14717_78']

Then you can use the prepared trades collection in the groupBy method of yours.

  • Related