从ArrayList中获取匹配的子集
我有一些 POJO
的 ArrayList
。比如说员工。
然后我得到另一个ArrayList
,其中仅包含该POJO
的“id”。(即员工)
现在,我想要一个来自主列表的匹配ID的子列表。
我可以通过迭代主列表并将其与另一个列表的每个 id 进行比较来实现此目的。
但是,我想找出其他最佳解决方案。
任何指示将不胜感激。
I have a ArrayList
of some POJO
. Let say Employee.
Then I am getting another ArrayList
which contains only 'id' of that POJO
.(i.e. Employee)
Now, I want a sub list of matching ids from my main list.
One way I can do it via iterating main list and comparing it with each id of another list.
But, I want to find out other optimum solution.
Any pointers would be appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
编辑:
O(n*log n)
O(n)
运行时间O(n)
总体运行时间:O(n*log n)
以下是整个过程:
初始化 Employee ArrayList:
创建一些随机的员工进行测试:
根据员工 ID 对员工 ArrayList 进行排序。
初始化一个仅包含员工 ID 的临时字符串 ArrayList:
这里我们创建一个新的员工对象,并为其分配我们要为其创建子列表的 id:
查找该 ID 的开始和结束索引:
创建一个子列表从开始和结束索引:
唯一的调整是
覆盖
Employee类中的equals(Object obj)
:我知道这有点棘手,但它需要
n*日志(n)
运行时间。Edit:
O(n*log n)
O(n)
running timeO(n)
Overall running time: O(n*log n)
Here is the whole procedure:
Initializing an Employee ArrayList:
Creating some random Employees to test:
Sorting the Employees ArrayList w.r.t their IDs.
Initializing a temporary ArrayList of String which contains only IDs of Employees:
Here we create a new Employee Object and assign it the id we want to create a sub-list for:
Find the start and end Index of that ID:
Create a sub-list from the start and end index:
Only tweak is to
Override
theequals(Object obj)
in Employee class:I know its a bit tricky but it takes
n*log(n)
running time.将 ids 放入 Set 中。然后,您可以迭代您的员工列表并测试它是否在您正在查找的集合中,而不会产生糟糕的
O(n^2)
运行时间。如果您想编写更漂亮的代码,您还可以查看 Maps.uniqueIndex 为自己构建一个 Map,然后您可以取出来。
Put the ids into a Set. Then you can iterate over your list of Employees and test whether it is in the set you are looking for without a bad
O(n^2)
running time.If you want to make prettier code, you could also look into Maps.uniqueIndex to build yourself a Map which you could then fetch out of.
无论如何,我必须迭代集合。最佳解决方案是使用一些可以为您完成此操作的库。 Guava 有谓词 在这种情况下这确实很有帮助。检查示例:
Anyway i have to iterate over collection. Optimum solution will be to use some library that can do this for you. Guava has Predicate which are realy helpfull in that case. Check the example:
什么类型有 id 字段?一种方法可能是在第一个 ArrayList 中数组的某个点处插入 POJO,该点等于员工的 id(例如,仅当它是整数时才有效)。
当然,这意味着您可以修改第一个 ArrayList 的插入。否则,循环遍历数组是我知道解决该问题的唯一方法。
What type has the id field? An approach could be that you insert the POJOs in the first ArrayList at a certain point of the array where the point is equals the id of the employee (this works only if it is an integer for example).
Of course this would mean that you are able to modify the insertion of the first ArrayList. Otherwise looping through the array is the only way I am aware of to solve that issue.