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

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

    Java 8 Stream API can be used for the purpose,

    ArrayList list1 = new ArrayList<>();
    
    list1.add("A");
    list1.add("B");
    list1.add("A");
    list1.add("D");
    list1.add("G");
    
    ArrayList list2 = new ArrayList<>();
    
    list2.add("B");
    list2.add("D");
    list2.add("E");
    list2.add("G");
    
    List noDup = Stream.concat(list1.stream(), list2.stream())
                         .distinct()
                         .collect(Collectors.toList());
    noDup.forEach(System.out::println);
    

    En passant, it shouldn't be forgetten that distinct() makes use of hashCode().

提交回复
热议问题