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.
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.
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,
val list_3 = (list_1 + list_2).distinct()