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

前端 未结 14 1525
予麋鹿
予麋鹿 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:18

    Firstly remove duplicates:

    arrayList1.removeAll(arrayList2);
    

    Then merge two arrayList:

    arrayList1.addAll(arrayList2);
    

    Lastly, sort your arrayList if you wish:

    collections.sort(arrayList1);
    

    In case you don't want to make any changes on the existing list, first create their backup lists:

    arrayList1Backup = new ArrayList(arrayList1);
    

提交回复
热议问题