How do I remove repeated elements from ArrayList?
To deduplicate an ArrayList
and maintain order, convert it to a LinkedHashSet
, then back to ArrayList
:
This will get you sorted faster than a greyhound chasing a rabbit. Now your list is free of duplicates and ready to go: [1, 2, 3]
.
Streams to the rescue (Java 8+)
Scared of order jumbling up? Java 8 brought us streams, just the gadget you need:
This way, your list keeps its initial sequence, all neat and clean.
Dealing with custom object duplicates
Creating custom objects? Override your equals()
and hashCode()
methods:
This is essential for set operations and Java 8+ stream actions to work like a well-oiled machine.
Parallel streams for the speed demons (Large lists)
Dealing with Godzilla-sized lists? A parallel stream might be your nitro boost:
Monitoring with benchmarks is sensible, you wouldn't race without a speedometer, would you?
Powerful Collections: Choose wisely!
Choosing the right collections can be as crucial as choosing the right Pokemon for battle:
HashSet
— The Flash, quick but unordered.LinkedHashSet
— The balanced warrior, keeps things in order while packing a punch.TreeSet
— OCD-friendly. Keeps everything sorted (not recommended for big lists, slower reactions than a sloth).
The power of external libraries
If you're all about that concise code life, Guava or Apache Commons Collections got you covered:
But remember, dependencies are like spices. Use them but don't overdo it.
Clean up before you dress up
You wouldn't put on a fresh shirt over a dirty one, right? Similarly, clear()
before adding the deduplicated elements:
This ensures your list doesn't cling onto the past and starts fresh.
Was this article helpful?