2013-10-03 14 views
25

Mam 2 arraylists obiektu string.Prosty sposób na porównanie 2 ArrayLists

List<String> sourceList = new ArrayList<String>(); 
List<String> destinationList = new ArrayList<String>(); 

Mam pewną logikę, w której muszę przetworzyć listę źródłową i otrzymam listę docelową. Lista docelowa będzie zawierać dodatkowe elementy dodane do listy źródłowej lub usunięte z listy źródłowej.

Moje oczekiwane wyjście to 2 ArrayList ciągu, w którym pierwsza lista powinna zawierać wszystkie ciągi usunięte ze źródła, a druga lista powinna zawierać wszystkie nowo dodane łańcuchy do źródła.

Każda prostsza metoda, aby to osiągnąć?

+6

Co próbowałeś do tej pory? –

+9

Przepraszam, koleś, przeczytaj 3 razy. Nie dostałem tego, o co prosisz. BTW, gdzie jest twój kod? –

+0

Służy do pętli, aby to osiągnąć. Poszukuję apisów stron trzecich .. – prabu

Odpowiedz

46

Konwersja wykazów Collection i używać removeAll

Collection<String> listOne = new ArrayList(Arrays.asList("a","b", "c", "d", "e", "f", "g")); 
    Collection<String> listTwo = new ArrayList(Arrays.asList("a","b", "d", "e", "f", "gg", "h")); 


    List<String> sourceList = new ArrayList<String>(listOne); 
    List<String> destinationList = new ArrayList<String>(listTwo); 


    sourceList.removeAll(listTwo); 
    destinationList.removeAll(listOne); 



    System.out.println(sourceList); 
    System.out.println(destinationList); 

wyjściowa:

[c, g] 
[gg, h] 

[EDIT]

inny sposób (bardziej jasne)

Collection<String> list = new ArrayList(Arrays.asList("a","b", "c", "d", "e", "f", "g")); 

    List<String> sourceList = new ArrayList<String>(list); 
    List<String> destinationList = new ArrayList<String>(list); 

    list.add("boo"); 
    list.remove("b"); 

    sourceList.removeAll(list); 
    list.removeAll(destinationList); 


    System.out.println(sourceList); 
    System.out.println(list); 

wyjściowa:

[b] 
[boo] 
+3

Nie zapomnij zaimplementować metod "równy" i "hashCode", jeśli chcesz porównać obiekty niestandardowe poprzez "removeAll". – Denis

0

O ile rozumiem, to poprawnie, myślę, że jest to najłatwiejszy do pracy z 4 list: - Twój SourceList - Twój DESTINATIONLIST - removedItemsList - newlyAddedItemsList

9

Powinno to sprawdzić, czy dwie listy są równe, najpierw wykonuje podstawowe kontrole (np wartości null i długości), a następnie sortuje i używa metody collections.equals, aby sprawdzić, czy są one równe.

public boolean equalLists(List<String> a, List<String> b){  
    // Check for sizes and nulls 

    if (a == null && b == null) return true; 


    if ((a == null && b!= null) || (a != null && b== null) || (a.size() != b.size())) 
    { 
     return false; 
    } 

    // Sort and compare the two lists   
    Collections.sort(a); 
    Collections.sort(b);  
    return a.equals(b); 
} 
+11

Sprawdzasz, czy listy są zerowe po sprawdzeniu ich rozmiarów .. to jest złe –

+0

'(a == null && b! = Null) || (a! = null && b == null)) ' Dla tej części możesz po prostu sprawdzić' (a! = b) ' – NurShomik

0

Najprostszym sposobem jest iterację list źródłowych i docelowych pojedynczo jak ten:

List<String> newAddedElementsList = new ArrayList<String>(); 
List<String> removedElementsList = new ArrayList<String>(); 
for(String ele : sourceList){ 
    if(destinationList.contains(ele)){ 
     continue; 
    }else{ 
     removedElementsList.add(ele); 
    } 
} 
for(String ele : destinationList){ 
    if(sourceList.contains(ele)){ 
     continue; 
    }else{ 
     newAddedElementsList.add(ele); 
    } 
} 

Choć może nie być bardzo skuteczne, jeśli list źródłowy i docelowy mają wiele elementów, ale na pewno jego prostsze.

4

Konwersja List do String i sprawdzić, czy ciągi są takie same czy nie

import java.util.ArrayList; 
import java.util.List; 



/** 
* @author Rakesh KR 
* 
*/ 
public class ListCompare { 

    public static boolean compareList(List ls1,List ls2){ 
     return ls1.toString().contentEquals(ls2.toString())?true:false; 
    } 
    public static void main(String[] args) { 

     ArrayList<String> one = new ArrayList<String>(); 
     ArrayList<String> two = new ArrayList<String>(); 

     one.add("one"); 
     one.add("two"); 
     one.add("six"); 

     two.add("one"); 
     two.add("two"); 
     two.add("six"); 

     System.out.println("Output1 :: "+compareList(one,two)); 

     two.add("ten"); 

     System.out.println("Output2 :: "+compareList(one,two)); 
    } 
} 
+3

, ale nie znasz kolejności! – Khatri

2

Odpowiedź jest podany w @dku-rajkumar postu.

ArrayList commonList = CollectionUtils.retainAll(list1,list2);

0
private int compareLists(List<String> list1, List<String> list2){ 
    Collections.sort(list1); 
    Collections.sort(list2); 

    int maxIteration = 0; 
    if(list1.size() == list2.size() || list1.size() < list2.size()){ 
     maxIteration = list1.size(); 
    } else { 
     maxIteration = list2.size(); 
    } 

    for (int index = 0; index < maxIteration; index++) { 
     int result = list1.get(index).compareTo(list2.get(index)); 
     if (result == 0) { 
      continue; 
     } else { 
      return result; 
     } 
    } 
    return list1.size() - list2.size(); 
} 
0

Jeśli wymogiem jest, aby zachować kolejność wstawiania oraz sprawdzić zawartość dwóch ArrayList następnie należy zrobić co następuje:

List<String> listOne = new ArrayList<String>(); 
List<String> listTwo = new ArrayList<String>(); 

listOne.add("stack"); 
listOne.add("overflow"); 

listTwo.add("stack"); 
listTwo.add("overflow"); 

boolean result = Arrays.equals(listOne.toArray(),listTwo.toArray()); 

ta zwróci true.

Jeśli jednak zmienić kolejność na przykład:

listOne.add("stack"); 
listOne.add("overflow"); 

listTwo.add("overflow"); 
listTwo.add("stack"); 

boolean result = Arrays.equals(listOne.toArray(),listTwo.toArray()); 

zwróci false jak zamawianie jest inna.

Powiązane problemy