Java中的关联数组

Gib*_*bbs 5 java dictionary list avro

我收到List<org.apache.avro.generic.GenericRecord>的数据内容如下所示(为清晰起见,使用了JSON表示法).如何使用Java最好地保存这些记录类型?

记录1:

   [
    {
      "serial_no" : "x",
      "data1" : "d"
    },
    {
     "serial_no" : "y",
     "data2" : "d2"
    },
    ............................MANY MORE
   ]
Run Code Online (Sandbox Code Playgroud)

记录2:

   [
    {
      "id":"x",
      "type":"A"
    },
    {
      "id" : "x",
      "type" : "B"
    },
    {
      "id" : "y",
      "type" : "A",
    },
    { 
      "id" : "y",
      "type" : "B"
    } 
   ]
Run Code Online (Sandbox Code Playgroud)

如您所见,每个serial number记录中都有两条记录.serial_no在record1中与idrecord2中相同.

我的目标是:找到这两条记录的最有效方法.

解决方案我认为:

像这样创建一个地图

      map.put("x", [map.put("A",List), map.put("B",List)]);
Run Code Online (Sandbox Code Playgroud)

但我觉得,它是一个复杂的结构.因为地图包含地图列表[each map is Map<String,List<Map<String,String>>>].

有什么建议?

编辑

记录中的每个条目都是avro GenericRecord

mvr*_*ijn 4

看起来您正在尝试使用 Java 解析 JSON。为什么不使用特定的库呢?就像基本的http://www.json.org/java/或 Google 的https://github.com/google/gson

否则,我不认为您提出的复杂结构特别慢。如果您认为获取数据更有效或更容易,您可能需要设计自己的对象类来保存数据。


编辑

根据您的问题,我认为 JSON 是您收到的格式,抱歉。

我只想为 GenericRecord 创建一个包装器,或者将其子类化。Comparable然后添加提取数据或进行排序所需的方法。

类似的东西

public class MyRecord extends GenericRecord implements Comparable<MyRecord>
{
    // Determine the type
    public int getType()
    {
        if ( this.get( "id") != null )
            return 2;
        return 1;
    }
    // Add methods that allow you to retrieve the serial field from any of the two record types
    public String getId()
    {
        if ( this.get( "id") != null )
            return (String)this.get("id");
        return (String)this.get("serial_no");
    }

    // add comparator methods that will allow you to sort the list, compare based on Id, etc
    @Override
    public int compareTo(MyRecord another) 
    {
        // Just a simple example
        return this.getId().compareTo( another.getId() );
    }
}
Run Code Online (Sandbox Code Playgroud)