没有迭代的过滤列表
在Java中是否可以根据某些条件过滤列表而不进行迭代?我有一个大小为 10000 的列表,其中充满了豆子,其中这些豆子具有布尔类型的属性。如果我想根据该布尔属性过滤该列表,是否需要迭代整个列表,或者还有其他方法吗?
Is it possible in Java to filter a List based on some criteria without iteration? I have a List of size 10000 full of beans where those beans have a property of type boolean. If I want to filter that list based on that boolean property is it necessary to iterate the whole List or there is some other way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您有一个包含 10000 件事的列表,并且您希望能够神奇地按照某些标准选择其中一些内容,而无需实际依次查看每一项并查看它是否符合条件?嗯...不。您也许能够找到一个对您隐藏迭代的库,但最终您将必须访问每个项目以查看它是否匹配。
You've got a list of 10000 things and you want to magically be able to select some of them by some criteria without actually going to each one in turn and seeing if it matches the criteria? Ummm... no. You might be able to find a library which will hide the iteration from you, but ultimately you're going to have to visit each item to see if it matches or not.
如果您的意思是不使用迭代器,那么答案是肯定的。例如:
根据
List
实现,与使用Iterator
和Iterator.remove()
相比,这可能是一种昂贵的实现过滤的方法。 (例如,如果列表是LinkedList
,则list.get(i)
和list.remove(i)
都是O (N)
,因此列表过滤的时间为O(N^2)
相比之下,使用迭代器
过滤同一列表的时间为O。 (N)
。)但是,如果您询问是否可以过滤您的列表而不检查列表中的每个元素,那么答案是否定的。您需要一些辅助数据结构,或者对属性进行排序的列表,以实现比
O(N)
过滤更好的效果。If you mean, without using an
Iterator
, then the answer is Yes. For example:Depending on the
List
implementation, this could be an expensive way of implementing filtering than using anIterator
andIterator.remove()
. (For instance, if list is aLinkedList
thenlist.get(i)
andlist.remove(i)
are bothO(N)
and hence the list filtering isO(N^2)
. By contrast, filtering the same list with anIterator
would beO(N)
.)However, if you are asking if you can filter your list without checking each element in the list, then the answer is No. You'd need some secondary data structure, or the list to be ordered on the property to achieve better than
O(N)
filtering.您可以编写一个实现 List 接口的包装类,并仅“隐藏”具有上述属性的所有 bean。然而,许多操作(例如每个基于索引的函数)效率非常低,因此这取决于您到底想对“过滤”列表执行什么操作。
You could write a wrapper class that implements the List interface and just "hides" all beans with the said property. However a lot of operations (e.g. every index based function) would be very inefficient, so it depends what exactly you want to do with the "filtered" List.
您可以使用 Java 8 中的流来执行此操作。假设您有一个电动汽车和非电动汽车的列表,并且您只想提取电动汽车:
You can do this using stream in Java 8. Assume you have a list of electric and non-electric cars and you want to extract only electric: