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

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

    Add ArrayList1, ArrayList2 and produce a Single arraylist ArrayList3. Now convert it into

    Set Unique_set = new HashSet(Arraylist3);
    

    in the unique set you will get the unique elements.
    Note

    ArrayList allows to duplicate values. Set doesn't allow the values to duplicate. Hope your problem solves.

    0 讨论(0)
  • 2020-11-28 12:07

    Here is one solution using java 8:

    Stream.of(list1, list2)
        .flatMap(Collection::stream)
        .distinct()
        // .sorted() uncomment if you want sorted list
        .collect(Collectors.toList());
    
    0 讨论(0)
  • 2020-11-28 12:09

    Java 8 Stream API can be used for the purpose,

    ArrayList<String> list1 = new ArrayList<>();
    
    list1.add("A");
    list1.add("B");
    list1.add("A");
    list1.add("D");
    list1.add("G");
    
    ArrayList<String> list2 = new ArrayList<>();
    
    list2.add("B");
    list2.add("D");
    list2.add("E");
    list2.add("G");
    
    List<String> 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().

    0 讨论(0)
  • 2020-11-28 12:09

    your nested for loop

     for(int j = 0; j < array2.size(); i++){
    

    is infinite as j will always equal to zero, on the other hand, i will be increased at will in this loop. You get OutOfBoundaryException when i is larger than plusArray.size()

    0 讨论(0)
  • 2020-11-28 12:09

    I got your point that you don't wanna use the built-in functions for merging or remove duplicates from the ArrayList. Your first code is running forever because the outer for loop condition is 'Always True'. Since you are adding elements to plusArray, so the size of the plusArray is increasing with every addition and hence 'i' is always less than it. As a result the condition never fails and the program runs forever. Tip: Try to first merge the list and then from the merged list remove the duplicate elements. :)

    0 讨论(0)
  • 2020-11-28 12:14

    You don't have to handcode this. The problem definition is precisely the behavior of Apache Commons CollectionUtils#collate. It's also overloaded for different sort orders and allowing duplicates.

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