Let says I have two arraylists:
JavaScript
x
List<String> arr = new ArrayList<>();
arryOne.add("Huey");
arryOne.add("Dewey");
arryOne.add("Louie");
List<String> arryTwo = new ArrayList<>();
arryTwo.add("Dewey");
arryTwo.add("Stuie");
Is there some convenient API or relatively simple way to add “Stuie” to arryOne while ignoring the redundant “Dewey” element?
I am sure I can brute force perform the add/ignore but was hoping someone might know of a convenience means through collections API or similar to do this in just a few lines of code. Thanks!
Advertisement
Answer
There isn’t, because List is a datatype that more or less explicitly means: Can contain duplicates.
In other words, List, if anything, has baked in that the second Dewey
is not redundant:
JavaScript
arr.addAll(arryTwo);
should result in: [Huey, Dewey, Louie, Dewey, Stuie]
.
Other data types are what you need. For example, a LinkedHashSet:
JavaScript
var set = new LinkedHashSet<String>();
var arr1 = List.of("Huey", "Dewey", "Louie");
var arr2 = List.of("Dewey", "Stuie");
set.addAll(arr1);
set.addAll(arr2);
System.out.println(set);
> [Huey, Dewey, Louie, Stuie]