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

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

    Add elements in first arraylist

    ArrayList firstArrayList = new ArrayList();
    
    firstArrayList.add("A");
    firstArrayList.add("B");
    firstArrayList.add("C");
    firstArrayList.add("D");
    firstArrayList.add("E");
    

    Add elements in second arraylist

    ArrayList secondArrayList = new ArrayList();
    
    secondArrayList.add("B");
    secondArrayList.add("D");
    secondArrayList.add("F");
    secondArrayList.add("G");
    

    Add first arraylist's elements in second arraylist

    secondArrayList.addAll(firstArrayList);
    

    Assign new combine arraylist and add all elements from both arraylists

    ArrayList comboArrayList = new ArrayList(firstArrayList);
    comboArrayList.addAll(secondArrayList);
    

    Assign new Set for remove duplicate entries from arraylist

    Set setList = new LinkedHashSet(comboArrayList);
    comboArrayList.clear();
    comboArrayList.addAll(setList);
    

    Sorting arraylist

    Collections.sort(comboArrayList);
    

    Output

     A
     B
     C
     D
     E
     F
     G
    

提交回复
热议问题