我有一个 List<Element> elements
,其中类 Element 具有属性 id
- 是龙。我也有List<Long> ids
.现在我需要从elements
列出具有 id
的对象ids
中存在的 Prop 列表。
我使用了这两个 for 循环,但我认为这不是最佳选择。
我怎样才能提高我的表现?
public class Element{
Long id;
public Element(Long id){
this.id = id;
}
public Long getId( ){
return id;
}
public static void main(String []args){
List<Element> elements= Arrays.asList(new Element(1),new Element(2),new Element(3), new Element(5), new Element(5));
List<Long> ids= Arrays.asList(3,4,1);
List<Element> returnList = new ArrayList<Alement>();
for(int i = 0; i < elements.size(); i++) {
for(int j = 0; j < ids.size(); j++) {
if (elements.get(i).getId() == ids.get(j))
returnList.add(elements.get(i));
}
}
}
}
最佳答案
How can i improve my performance?
你可以使用 HashMap
为您的元素使用 id
作为键。然后,在您的 ids
List
上使用单个循环进行查找。
HashMap
具有恒定的查找复杂度。
关于java - 从具有指定 ID 的另一个列表中获取元素列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30868275/