Skip to content
Advertisement

ArrayList – Add Elements, Passively Skipping Redundant Elements

Let says I have two arraylists:

JavaScript

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

should result in: [Huey, Dewey, Louie, Dewey, Stuie].

Other data types are what you need. For example, a LinkedHashSet:

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement