【问题标题】:What is the Grooviest way to model this data?对这些数据建模的 Grooviest 方法是什么?
【发布时间】:2016-02-12 17:39:38
【问题描述】:

我正在使用 Groovy 读取具有以下字段的 CSV 文件:

  Code   Name        Class
  ---    -----       ----
  1701   Enterprise  Constitution      
  1864   Reliant     Miranda 

在 Groovy 中表示这些数据的最佳方式是什么?

我在想HashMap,其中 Code 是键,值是具有两个字段(Name 和 Class)的 POGO .但是有没有更时髦的方法?

【问题讨论】:

    标签: java groovy object-model


    【解决方案1】:

    使用 POGO 和 TupleConstructor AST 转换,将 CSV 解析为列表通常非常简单:

    @Grapes(
        @Grab(group='org.apache.commons', module='commons-csv', version='1.2')
    )
    
    import groovy.transform.*
    import org.apache.commons.csv.*
    
    @ToString
    @TupleConstructor
    class Test {
        int code
        String name
        String type
    }
    
    def text = ''' Code,Name,Class
    1701,Enterprise,Constitution
    1864,Reliant,Miranda'''
    
    def parsed = CSVParser.parse(text, CSVFormat.EXCEL.withHeader().withIgnoreSurroundingSpaces().withQuote(null))
    
    def result = parsed.getRecords().collect { new Test(it.Code as int, it.Name, it['Class']) }
    assert '[Test(1701, Enterprise, Constitution), Test(1864, Reliant, Miranda)]' == result.toString()
    assert 'Enterprise' == result.find({ it.code == 1701 }).name
    

    【讨论】:

      【解决方案2】:

      使用带有code 的普通Map 作为密钥就足够了。这取决于你需要做什么。如果您需要将这些数据转换为Map,这就是您要走的路。

      但是 groovy 在数据处理方面非常灵活,您还可以创建 POGO 并将此 CSV 数据转换为列表。它可以很容易地按code 或您需要的任何内容进行分组。

      另外,也许不需要创建 POGO?在这种情况下,请使用 code 一个键来.. Map。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-03-29
        • 2014-05-17
        • 2011-05-27
        • 2011-02-17
        • 1970-01-01
        相关资源
        最近更新 更多