Reputation: 65
I have two list :
list1 = [1,2,3]
list2 = [2,3,4]
I want to take all the element of two list with no same value and each element will repeat once example :
list3 = [1,2,3,4]
list3
will get element of list1
and list2
.
Upvotes: 1
Views: 124
Reputation: 300
You can do this properly with :
List<Integer> A = Arrays.asList(1, 2, 3);
List<Integer> B = Arrays.asList(2,3,4);
List<Integer> D = ListUtils.subtract(B, A);// contain 4
Output
List<Integer> C = ListUtils.union(A, D); // 1,2,3,4
Upvotes: 1
Reputation: 59950
The quick way is to use a Set for example :
Input
List<Integer> list1 = Arrays.asList(1,2,3);
List<Integer> list2 = Arrays.asList(2,3,4);
Add your lists to Set
Set<Integer> set = new TreeSet<>();
set.addAll(list1);
set.addAll(list2);
Output
[1, 2, 3, 4]
Upvotes: 3
Reputation: 886
Add the unique values from the 2nd list to the first one:
for (int i = 0; i < list2.size(); i++)
if (!list1.contains(list2.get(i))
list1.add(list2.get(i));
Upvotes: 1