2015-06-16 81 views
1

我有List<Element> elements,其中class元素的屬性爲id - 它很長。我也有List<Long> ids。現在我需要從elements列表中有id道具的列表對象存在於ids列表中。從指定ID的另一個列表中獲取元素列表

我用這兩個循環,但我認爲這不是最好的選擇。

我該如何提高自己的表現?

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)); 
     } 
    } 

    } 
} 
+0

PLZ份額我們的代碼。 – Bikku

+0

*我用這兩個for循環*你可以發佈你的循環,讓我們明白你做了什麼? – Blip

+0

我用例子編輯 – user3802040

回答

4

如何提高我的表現?

您可以使用HashMap作爲您的元素使用id作爲關鍵。然後,在您的idsList上使用單個循環進行查找。 HashMap具有不變的查找複雜度。

+0

'HashSet'會更好。 – OldCurmudgeon

+0

由於HashSet是由HashMap支持的,我不完全確定這一點,你能給我一個提示,爲什麼它會更好(除了明顯的設置屬性,我認爲最有可能的是OP所期望的)? – cygery

+0

由於'Set'只保存一組項目,'Map'包含'Key/Value'對。 OP只需要不存在從鍵到值的轉換,所以'Set'更合適.. – OldCurmudgeon

1

做一個集ID是這樣的:

Set<Long> idSet = new HashSet<>(ids); 
    List<Element> selected = elements.stream() 
     .filter(element -> idSet.contains(element.getId())) 
     .collect(Collectors.toList()); 
0

可以使用Google Guavafiltering爲:

Iterable<Element> filteredElements = Iterables.filter(elements, new Predicate<Element>() { 
     @Override 
     public boolean apply(Element element) { 
      return ids.contains(element.getId()); 
     } 
    });