4
\$\begingroup\$

I have these invoices listed:

def invoices = [
'LEDES98BI V2',
'LINE|INVOICE_DATE|INVOICE_NUMBER|INVOICE_TOTAL',
'1|20150301|INV-Error_Test1|22',
'2|20150301|INV-Error_Test1|24',
'3|20150301|INV-Error_Test2|26',
'4|20150301|INV-Error_Test2|28,']

I am trying to do groupBy on the above collection with INVOICE_NUMBER and trying to achieve map with INVOICE_NUMBER and lines as values:

def lines = invoices*.split('\\|').findAll{ it.size()>1 }
def heads = lines.first()
def invoiceMap = lines.tail().collect{ [heads, it].transpose().collectEntries() }.groupBy{ it.INVOICE_NUMBER }

If I print invoiceMap I get what I intended as this map:

 [INV-Error_Test1:[[LINE:1, INVOICE_DATE:20150301, INVOICE_NUMBER:INV-Error_Test1, INVOICE_TOTAL:22], 
 [LINE:2, INVOICE_DATE:20150301, INVOICE_NUMBER:INV-Error_Test1, INVOICE_TOTAL:24]], 
 INV-Error_Test2:[[LINE:3, INVOICE_DATE:20150301, INVOICE_NUMBER:INV-Error_Test2, INVOICE_TOTAL:26], 
 [LINE:4, INVOICE_DATE:20150301, INVOICE_NUMBER:INV-Error_Test2, INVOICE_TOTAL:28,]]
 ]

But if the INVOICE_NUMBER has any white spaces with it in the invoices map my code doesn't work, so I tweaked the code as below to get it working:

 def invLineDetails = lines.tail().collect{ [heads, it].transpose().collectEntries() }.groupBy{it[it.keySet().find{it.contains('INVOICE_NUMBER')}] }

Can this code be optimized/refactored further?

Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Jun 11, 2015 at 19:26
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

I could not produce an error when an invoice number contains white spaces. I made some minor tweaks.

def invoices = [
'LEDES98BI V2',
'LINE|INVOICE_DATE|INVOICE_NUMBER|INVOICE_TOTAL',
'1|20150301|INV-Error_Test1|22',
'2|20150301|INV-Error_Test1|24',
'3|20150301|INV-Error_Test2|26',
'4|20150301|INV-Error_Test2|28,',
'5|20150301|INV WITH WHITESPACE|29,']
def lines = invoices
 .findAll { it.contains('|') }
 .collect { it.tokenize('|') }
def headers = lines.first()
def invoiceMap = lines.tail().collect{
 [headers, it].transpose().collectEntries()
}.groupBy{ it.INVOICE_NUMBER }
answered Aug 13, 2015 at 2:30
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.