2013-10-09 51 views
2

我有一個String數組和一個List<String>。我想要做的是使用具有較大尺寸的變量,並將其用作刪除較小變量的值的基礎。我也想獲得更大尺寸變量的值不存在於另一箇中。請注意,兩個變量在數據類型上有所不同的原因是String[] group變量是來自jsp頁面的複選框組,而List<String> existingGroup是數據庫中的ResultSet。例如:比較和刪除列表中不存在的元素java

String[] group包含:

Apple 
Banana 
Juice 
Beef 

List<String> existingGroup包含:

Apple 
Beef 
Lasagna 
Flower 
Lychee 

而且,由於這兩個變量的大小而變化,它仍然應該正確地刪除值。

我有什麼到目前爲止

if(groupId.length >= existingGroup.size()) { 
     for(int i = 0; i < groupId.length; i++) { 
      if(! existingGroup.contains(groupId[i])) { 
       if(existingGroup.get(existingGroup.indexOf(groupId[i])) != null) { 
        // I'm unsure if I'm doing this right 
       } 
      } 
     } 
    } else { 
     for(int i = 0; i < existingGroup.size(); i++) { 
      // ?? 
     } 
    } 

感謝。

+1

請參閱此堆棧溢出職位[更加清晰]( http://stackoverflow.com/questions/163998/classical-set-operations-for-java-util-collection) – bsingh

回答

3

您可以使用List接口提供的方法。

list.removeAll(Arrays.asList(array)); // Differences removed 

list.retainAll(Arrays.asList(array)); // Same elements retained 

根據您的需求。

+0

這兩種方法都會返回一個「boolean」... –

4

好吧,我會開始將您的數組轉換爲List。所以,做

List<String> input = Arrays.asList(array); 
//now you can do intersections 
input.retainAll(existingGroup); //only common elements were left in input 

或者,如果你想要的是不常見的元素,只是做

existingGroup.removeAll(input); //only elements which were not in input left 
input.removeAll(existingGroup); //only elements which were not in existingGroup left 

選擇是你:-)

+0

這很棒,但我也需要它們之間的差異,不僅是共同的元素。我認爲我在文章開頭的發言很模糊,所以我重新說了一遍。 – makalshrek

+0

'retainAll'抱怨變量必須是'boolean'類型。這是獲得共同元素的正確方法嗎? – makalshrek

+0

對不起,編輯我的asnwer –