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

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

    Instead of the code you wrote, you may use ArrayList.addAll() to merge the lists, Collections.sort() to sort it and finally traverse of the resulting ArrayList to remove duplicates. The aggregate complexity is thus O(n)+O(n*log(n))+O(n) which is equivalent to O(n*log(n)).

    0 讨论(0)
  • 2020-11-28 12:29
    List<String> listA = new ArrayList<String>();
    
        listA.add("A");
        listA.add("B");
    
    List<String> listB = new ArrayList<String>();
    
        listB.add("B");
        listB.add("C");
    
    Set<String> newSet = new HashSet<String>(listA);
    
        newSet.addAll(listB);
    List<String> newList = new ArrayList<String>(newSet);
    
    System.out.println("New List :"+newList);
    

    is giving you New List :[A, B, C]

    0 讨论(0)
提交回复
热议问题