我想通过 Java 中的属性获取列表中对象的索引。
例子:
List<MyObj> list = new ArrayList<>();
list.add(new MyObj("Ram");
list.add(new MyObj("Girish");
list.add(new MyObj("Ajith");
list.add(new MyObj("Sai");
public class MyObj {
public String name;
public MyObj(String name){
this.name=name;
}
}
Run Code Online (Sandbox Code Playgroud)
现在,我想获取包含名称为“Girish”的对象的索引。请让我知道JAVA中的代码。
mic*_*czy 12
如果你想要一个带有流的解决方案,请使用这个:
int index = IntStream.range(0, list.size())
.filter(i -> list.get(i).name.equals(searchName))
.findFirst()
.orElse(-1);
Run Code Online (Sandbox Code Playgroud)
如果您有一个List,您所能做的就是迭代每个元素并检查所需的属性。这是O(n)。
public static int getIndexOf(List<MyObj> list, String name) {
int pos = 0;
for(MyObj myObj : list) {
if(name.equalsIgnoreCase(myObj.name))
return pos;
pos++;
}
return -1;
}
Run Code Online (Sandbox Code Playgroud)
如果您想提高性能。然后你就可以实现你自己的数据结构。请注意,关键特征是您的键属性应该是 a 的键,HashMap并且 a 的值HashMap应该是索引。然后你就得到了O(1)的性能。
public static final class IndexList<E> extends AbstractList<E> {
private final Map<Integer, E> indexObj = new HashMap<>();
private final Map<String, Integer> keyIndex = new HashMap<>();
private final Function<E, String> getKey;
public IndexList(Function<E, String> getKey) {
this.getKey = getKey;
}
public int getIndexByKey(String key) {
return keyIndex.get(key);
}
@Override
public int size() {
return keyIndex.size();
}
@Override
public boolean add(E e) {
String key = getKey.apply(e);
if (keyIndex.containsKey(key))
throw new IllegalArgumentException("Key '" + key + "' duplication");
int index = size();
keyIndex.put(key, index);
indexObj.put(index, e);
return true;
}
@Override
public E get(int index) {
return indexObj.get(index);
}
}
Run Code Online (Sandbox Code Playgroud)
演示:
IndexList<MyObj> list = new IndexList<>(myObj -> myObj.name);
list.add(new MyObj("Ram"));
list.add(new MyObj("Girish"));
list.add(new MyObj("Ajith"));
list.add(new MyObj("Sai"));
System.out.println(list.getIndexByKey("Ajith")); // 2
Run Code Online (Sandbox Code Playgroud)
MrB*_*MrB -3
indexOf()将返回值第一次出现的索引。例如:
int myIndex = list.indexOf("Ram")
(请注意,虽然您的数组列表不包含“Ram”,但它包含一个MyObj带有name“Ram”类型的对象)
请记住 ArrayList 从 0 开始,而不是从 1 开始。
| 归档时间: |
|
| 查看次数: |
15579 次 |
| 最近记录: |