Simple way to compare 2 ArrayLists

后端 未结 10 1866
没有蜡笔的小新
没有蜡笔的小新 2020-11-30 00:50

I have 2 arraylists of string object.

List sourceList = new ArrayList();
List destinationList = new ArrayList

        
10条回答
  •  感情败类
    2020-11-30 01:10

    Convert Lists to Collection and use removeAll

        Collection listOne = new ArrayList(Arrays.asList("a","b", "c", "d", "e", "f", "g"));
        Collection listTwo = new ArrayList(Arrays.asList("a","b",  "d", "e", "f", "gg", "h"));
    
    
        List sourceList = new ArrayList(listOne);
        List destinationList = new ArrayList(listTwo);
    
    
        sourceList.removeAll( listTwo );
        destinationList.removeAll( listOne );
    
    
    
        System.out.println( sourceList );
        System.out.println( destinationList );
    

    Output:

    [c, g]
    [gg, h]
    

    [EDIT]

    other way (more clear)

      Collection list = new ArrayList(Arrays.asList("a","b", "c", "d", "e", "f", "g"));
    
        List sourceList = new ArrayList(list);
        List destinationList = new ArrayList(list);
    
        list.add("boo");
        list.remove("b");
    
        sourceList.removeAll( list );
        list.removeAll( destinationList );
    
    
        System.out.println( sourceList );
        System.out.println( list );
    

    Output:

    [b]
    [boo]
    

提交回复
热议问题