简体   繁体   English

如何将记录放入LinkedHashMap Java映射中或如何创建数据结构?

[英]How to put record in map of linkedhashmap java or how to create data structure?

How to put record in : 如何记录:

Map<String, LinkedHashMap<String, String>> fileRecords = new LinkedHashMap<String, LinkedHashMap<String,String>>();

I have two files in the same format, i have to create the data structure for both of them, and then compare the data structure to identify the differences for each CAID-find the blocks and compare the data. 我有两个格式相同的文件,我必须为它们两个都创建数据结构,然后比较该数据结构以识别每个CAID的区别-查找块并比较数据。

在此处输入图片说明

So accordingly i tried to read the file line by line. 因此,我试图逐行读取文件。 confused of what should i try to put the records in map or in arraylist (I have to follow the insertion order). 我应该如何将记录放入map或arraylist中(我必须遵循插入顺序)感到困惑。

Take ID as unique, for unique id, i want to store the corresponding block and data. 将ID作为唯一ID,对于唯一ID,我想存储相应的块和数据。

The decision to use a Map or a List or a Set lies on the purpose of the data being read. 决定使用Map还是List或Set取决于读取数据的目的。

  • if you need to index the data (eg by ID), then use a Map 如果您需要索引数据(例如,按ID),则使用Map
  • else, if you want to iterate through the data in order, I would recommend a List or Set collection. 否则,如果您要按顺序遍历数据,则建议使用List或Set集合。 If your dataset does not support duplicates I recommend you a Set, or a List if it will have duplicates. 如果您的数据集不支持重复项,那么我建议您使用一个Set或List(如果它具有重复项)。

About the code using Map, the piece of code below groups Block and Data per ID: 关于使用Map的代码,下面的代码将每个ID的Block和Data分组:

public void read() {
   Map<String, LinkedHashMap<String, String>> fileRecords = new LinkedHashMap<>();
   String id, block, data;

   //while(dataInFile()) {
       // I assume data is read row by row into vars id, block and data

       // get the block map for the just read ID
       LinkedHashMap<String, String> blockRecords = fileRecords.get(id);

       // first Block for the ID
       if (blockRecords == null) {
           blockRecords = new LinkedHashMap<>();
           fileRecords.put(id, blockRecords);
       }

       // read data and block
       blockRecords.put(block, data);
   }

This code also allows you to group block and data if the IDs are not sorted in the file. 如果未在文件中对ID进行排序,则此代码还允许您将块和数据分组。 If the ID is always an integer, I recommend you to use an Integer instead of String. 如果ID始终是整数,建议您使用Integer而不是String。 It saves memory and CPU during the matching. 匹配期间可以节省内存和CPU。

Also, if data in your file is not just these 3 fields, I'd recommend you to use objects instead. 另外,如果文件中的数据不只是这3个字段,我建议您改用对象。 Then you will need to be more mindful about the usage of the data to design the object model. 然后,您将需要更加注意使用数据来设计对象模型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM