带和不带空格的 Groovy GroupBy 字段 [英] Groovy GroupBy field with and without white spaces

查看:19
本文介绍了带和不带空格的 Groovy GroupBy 字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有发票清单如下

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,']

我正在尝试使用 INVOICE_NUMBER 对上面的集合进行 groupBy 并尝试使用 INVOICE_NUMBER 和行作为值来实现地图,下面的代码是这样做的

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, below code does it

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 }

如果我打印 invoiceMap 我得到我想要的如下地图

If I print invoiceMap I get what I intended as below 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,]]
  ]

但是,如果 INVOICE_NUMBERinvoices 映射中有任何空格,我的代码不起作用.有人可以帮助我让我的代码在 INVOICE_NUMBER 上使用空格吗?

But but if the INVOICE_NUMBER has any white spaces with it in the invoices map my code doesnt work. Can someone help me to make my code work with white spaces on INVOICE_NUMBER?

推荐答案

使用合适的 CSV 解析器,而不是滚动你自己的.

Use a proper CSV parser, rather than rolling your own.

@Grab('com.xlson.groovycsv:groovycsv:1.0')
import static com.xlson.groovycsv.CsvParser.parseCsv

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,']

def data = parseCsv(invoices.drop(1).join('
'), separator:'|')
def invoiceMap = data.collect().groupBy { it.INVOICE_NUMBER }

或者在列标题中加一个空格:

Or with a space in the column title:

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,']

def data = parseCsv(invoices.drop(1).join('
'), separator:'|')
def invoiceMap = data.collect().groupBy { it.'INVOICE NUMBER' }

这篇关于带和不带空格的 Groovy GroupBy 字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆