0

I have two lists:

list_1 = [1, 2, 3, 4, 5]

list_2 = [1, 3, 5, 6, 7]

I want to get a list like this:

list_3 = [1, 2, 3, 4, 5, 6, 7]

No need to sort in ascending order, Thanks.

5
  • From your example it seems you want a disjoint union, case in which convert to set, merge, convert back to list. Commented Mar 25, 2020 at 13:58
  • yes. i want like you said. Commented Mar 25, 2020 at 14:00
  • Does this answer your question? How to merge two ArrayLists without duplicates? Commented Mar 25, 2020 at 14:05
  • val list_3 = (list_1 + list_2).distinct() Commented Mar 25, 2020 at 14:09
  • thanks pro. I did it. Commented Mar 25, 2020 at 14:33

2 Answers 2

1

You can do something like this following by using union operator

fun temp()
{
    val firstList = arrayListOf(1,2,3,4,5)
    val secondList = arrayListOf(1,3,5,6,7)
    val finalList = firstList.union(secondList)
    println("First list : ${firstList}")
    println("Second list : ${secondList}")
    println("Final list : ${finalList}")
}

InsecondList contains common elements 1,3 and 5 as the firstList, It was removed in the finalList. You can also use distinct operator according to your needs.

Sign up to request clarification or add additional context in comments.

Comments

0

If I understand correctly, you want entries from both lists, but they must appear only once. I assume from your last statement that the order does not matter. In that case this would be perfect for a Set. A Set is a Collection, so you can iterate through all the elements just as, for example, with a List.

EDIT

Code snippets:

Integer[] a = {1,2,3};
Integer[] b = {2,3,4};

Set<Integer> s = new HashSet<>();

s.addAll(Arrays.asList(a));
s.addAll(Arrays.asList(b));

for (int i : s) {
    System.out.print(i + ", ");
}
System.out.println();

If your integers are already in a primitive array:

int[] c = {1,2,3};
int[] d = {2,3,4};

Set<Integer> S = new HashSet<>();

S.addAll(Arrays.asList(Arrays.stream(c).boxed().toArray(Integer[]::new)));
S.addAll(Arrays.asList(Arrays.stream(d).boxed().toArray(Integer[]::new)));

for (int i : S) {
    System.out.print(i + ", ");
}
System.out.println();

For both of these the output is:

1, 2, 3, 4, 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.