[英]Find index of an object in ArrayList depending on the value of an attribute in Java
I am using Java 7. Is it possible to get the index of an Object in an ArrayList depending on a particular attribute value. 我正在使用Java 7.是否可以根据特定的属性值获取ArrayList中的Object索引。 eg:
例如:
class Abc{
String first_name;
String last_name;
// getter and setters...
}
Now 现在
List<Abc> abcList = new ArrayList();
Abc abcObj = new Abc();
abcObj.setFirst_name("Jeet");
abcObj.setLast_name("Adhikari");
abcList.add(abcObj);
Abc abcObj2 = new Abc();
abcObj2.setFirst_name("John");
abcObj2.setLast_name("Something");
abcList.add(abcObj2);
Now is there any better way without iterating to get the index of the object in abcList where name = "John" . 现在有没有更好的方法没有迭代来获取abcList中对象的索引,其中name =“John” 。
No, but you could use a HashMap instead with first name as key
and the complete object as value
不,但您可以使用HashMap,而使用名字作为
key
,将完整对象作为value
HashMap<String, Abc> abcMap = new HashMap<String, Abc>();
Abc abcObj = new Abc();
abcObj.setFirst_name("Jeet");
abcObj.setLast_name("Adhikari");
abcMap.put(abcObj.getFirst_name(), abcObj);
Abc abcObj2 = new Abc();
abcObj2.setFirst_name("John");
abcObj2.setLast_name("Something");
abcMap.put(abcObj2.getFirst_name(), abcObj2);
And then you can simply get the full object by calling for eg 然后你可以通过调用eg来简单地获得完整的对象
Abc objectByKey = abcMap.get("John");
I hope this alternative solution is also ok for you 我希望这个替代解决方案也适合您
As your list is an ArrayList, it can be assumed that it is unsorted. 由于您的列表是ArrayList,因此可以假定它是未排序的。 Therefore, there is no way to search for your element that is faster than O(n).
因此,无法搜索比O(n)更快的元素。
If you can, you should think about changing your list into a Set (with HashSet as implementation) with a specific Comparator for your sample class. 如果可以,您应该考虑将列表更改为Set(使用HashSet作为实现),并为您的示例类使用特定的Comparator。
Another possibility would be to use a HashMap. 另一种可能性是使用HashMap。 You can add your data as Sample (please start class names with an uppercase letter) and use the string you want to search for as key.
您可以将数据添加为Sample(请使用大写字母启动类名称)并使用要搜索的字符串作为键。 Then you could simply use
然后你可以简单地使用
Sample samp = myMap.get(myKey);
If there can be multiple samples per key, use Map>, otherwise use Map<String, Sample>
. 如果每个键可以有多个样本,请使用Map>,否则使用
Map<String, Sample>
。 If you use multiple keys, you will have to create multiple maps that hold the same dataset. 如果使用多个键,则必须创建包含相同数据集的多个映射。 As they all point to the same objects, space shouldn't be that much of a problem.
因为它们都指向相同的对象,所以空间应该不是那么大的问题。
There are 2 solutions: 有两种解决方案:
arrayList.indexOf(value)
arrayList.indexOf(value)
这样的迭代 java.util.HashSet
instead of java.util.ArrayList
java.util.HashSet
而不是java.util.ArrayList
我不知道你的解决方案背后的要求,但我会考虑使用LinkedHashMap而不是ArrayList。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.