Finding the different elements between two ArrayLists in Java

后端 未结 6 1278
滥情空心
滥情空心 2021-02-06 05:43

How can I know the different element between 2 array list in java? I need the exact element not a Boolean value which can be retrieved using removeAll().

6条回答
  •  遥遥无期
    2021-02-06 06:05

    import java.util.ArrayList;
    import java.util.Collection;
    import java.util.HashSet;
    import java.util.List;
    import java.util.Set;
    
    public class CompareTwoList {
        public CompareTwoList() {
            // TODO Auto-generated constructor stub
        }
    
        public static void main(String[] args) {
            List ls1 = new ArrayList();
            ls1.add("a");
            ls1.add("b");
            ls1.add("c");
            ls1.add("d");
    
            List ls2 = new ArrayList();
            ls2.add("a");
            ls2.add("b");
            ls2.add("c");
            ls2.add("d");
            ls2.add("e");
    
            Set set1 = new HashSet();
            set1.addAll(ls1);
    
            Set set2 = new HashSet();
            set2.addAll(ls2);
            set2.removeAll(set1);
    
            //set.addAll(ls1);
            //set.addAll(ls1);
    
            for (String diffElement : set2) {
                System.out.println(diffElement.toString());
            }
        }
    }    
    

提交回复
热议问题