Merging two arrayLists into a new arrayList, with no duplicates and in order, in Java

前端 未结 14 1510
予麋鹿
予麋鹿 2020-11-28 11:50

I am trying to \"combine\" two arrayLists, producing a new arrayList that contains all the numbers in the two combined arrayLists, but without any duplicate elements and the

14条回答
  •  一生所求
    2020-11-28 12:23

    **Add elements in Final arraylist,**
    **This will Help you sure**
    
    import java.util.ArrayList;
    import java.util.List;
    
    public class NonDuplicateList {
    
    public static void main(String[] args) {
    
        List l1 = new ArrayList();
        l1.add("1");l1.add("2");l1.add("3");l1.add("4");l1.add("5");l1.add("6");
        List l2 = new ArrayList();
        l2.add("1");l2.add("7");l2.add("8");l2.add("9");l2.add("10");l2.add("3");
        List l3 = new ArrayList();
        l3.addAll(l1);
        l3.addAll(l2);
        for (int i = 0; i < l3.size(); i++) {
            for (int j=i+1; j < l3.size(); j++) {
                 if(l3.get(i) == l3.get(j)) {
                     l3.remove(j);
                }
            }
        }
        System.out.println(l3);
    }
    

    }

    Output : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

提交回复
热议问题