Java,在对象列表中搜索? [英] Java, searching within a list of objects?

查看:30
本文介绍了Java,在对象列表中搜索?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在以最快的速度实现这一目标的过程中有点迷失.我有一大堆具有基本变量属性(带有 getter/setter)的对象列表,我需要在此列表中进行搜索以查找列表中与给定参数匹配的对象

I'm a bit lost on the way to make this happen the fastest. I have a large list of objects that have basic variable attributes (with getters / setters) and I need to do a search in this list to find the objects within the list that match a given parameter

我已经找到了如何进行常规列表搜索,但我需要,例如,为列表中的每个对象搜索调用 getName() 的结果的值,并获取结果与我的匹配的对象输入.

I have found how to do a regular list search but I need to, for example search for the value of the result of doing a call getName() for each object in the list and get objects that have a result that matches my input.

类似于下面的第三个参数是方法调用的结果,第二个参数是我想要找到的.

Something like below where the third argument is the result of the method call and the second is what I am trying to find.

   int index = Collections.binarySearch(myList, "value", getName());

感谢任何建议

推荐答案

如果你只是作为一次性操作需要找到 getName() 是特定值的对象,那么可能没有多少魔法可能:循环遍历列表,对每个对象调用 getName(),对于匹配的对象,将它们添加到您的结果列表中.

If you just as a one-off operation need to find the object(s) whose getName() is a particular value, then there's probably not much magic possible: cycle through the list, call getName() on each object, and for those that match, add them to your list of results.

如果 getName() 是一个代价高昂的操作,而且如果给定的对象肯定不会返回匹配的值,还有其他一些先验的方法,那么显然你可以在循环时建立这个过滤".

If getName() is an expensive operation and there's some other way of a-priori working out if a given object definitely won't return a matching value, then obviously you can build in this 'filtering' as you cycle through.

如果您经常需要为给定的 getName() 获取对象,则保留 [getName() 的结果-> 对象 -> 匹配列表] 的索引(例如在 HashMap 中).您需要决定如何以及是否需要使此索引"与实际列表保持同步.

If you frequently need to fetch objects for a given getName(), then keep an index (e.g. in a HashMap) of [result of getName()->object -> list of matches]. You'll need to decide how and if you need to keep this "index" in synch with the actual list.

另请参阅使用 binarySearch() 但保持列表维护的另一个提议.这样一来,插入比使用映射和未排序列表更昂贵,但如果与查找相比插入不频繁,那么它的优点是只需要维护一个结构.

See also the other proposition to use binarySearch() but to keep the list maintained. This way, inserts are more expensive than with a map and unsorted list, but if inserts are infrequent compared to lookups, then it has the advantage of only needing to maintain one structure.

这篇关于Java,在对象列表中搜索?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆