简体   繁体   English

遍历数组列表Java

[英]looping through array lists Java

I am reading a list of items from an excel sheet. 我正在从Excel工作表中读取项目列表。 Each item name has a parent item name defined (as a separate column) from the same list. 每个项目名称都有一个从同一列表定义的父项目名称(作为单独的列)。 So this forms a tree hierarchy in which one item is a parent of the other in the same list and there are also multiple children for a parent. 因此,这形成了一个树层次结构,其中一个项目是同一列表中另一个项目的父项,并且父项也有多个子项。 The item names are not unique in the whole list. 项目名称在整个列表中不是唯一的。 Items are unique only under a particular parent. 项目仅在特定父项下是唯一的。

The Id for each item is generated while reading from input file. 从输入文件读取时,将生成每个项目的ID。 Now I want to get for each item the Id of its parent item. 现在,我想为每个项目获取其父项目的ID。

for a current record being read from the file, the parent item can be present down the line which we have not yet read, and hence we do not know the id of its parent. 对于从文件中读取的当前记录,可以在我们尚未读取的行下显示父项,因此我们不知道其父项的ID。

when I think of a logic it results in looping through array list and hashmap key sets repeatedly to get it. 当我想到一种逻辑时,它会导致反复遍历数组列表和hashmap键集来获取它。

I need help to get a better logic to solve this. 我需要帮助以获得更好的逻辑来解决此问题。 thanks in advance! 提前致谢!

EDIT 1: 编辑1:

Now I have problem in defining the structure of Excel sheet itself. 现在我在定义Excel工作表本身的结构时遇到问题。 I need it to be user friendly. 我需要它对用户友好。 How can I define a parent for an item record, when the names are not unique? 名称不唯一时,如何为项目记录定义父项? should I force the user to provide excel in the hierarchy order itself so that I can easily identify the parent for a child item? 我应该强迫用户自己按层次结构顺序提供excel,以便我可以轻松地标识子项的父项吗?

You could use a simple 您可以使用一个简单的

HashMap<Parent, List<Child>> to allow multiple values to be stored with each parent key -simply append children as needed to the keyed list. HashMap<Parent, List<Child>>允许与每个父键一起存储多个值-只需根据需要将子级附加到键列表中。 Alternatively, consider using a MultiMap to hold your data. 或者,考虑使用MultiMap来保存数据。

You can simply read the items one time and create a HashMap of (name, id). 您可以一次简单地阅读项目并创建一个(名称,ID)的HashMap。
And then iterate on the items again and assign the parent id, getting it from the HashMap. 然后再次遍历这些项目并分配父ID,从HashMap获取它。
In this way you will iterate only 2 times on the list of items, which will give it time complexity of O(n). 这样,您将仅在项目列表上迭代2次,这将使其时间复杂度为O(n)。

But if you don't have unique names then it may be possible that you don't find a unique parent for an item, if you only have it's parents name on the item. 但是,如果您没有唯一的名称,那么,如果在项目上仅具有其父名称,则可能找不到该项目的唯一父项。

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

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