Remove duplicates object in list java
ArrayList in Java allows adding duplicate elements but sometimes there may be a need to remove duplicates from a list. In this post we'll talk about the ways to remove duplicate elements from an ArrayList in Java. Options you have are as follows. Show
Let's see examples of all these options one by one. Read Also: Java Collections Framework Removing duplicates from ArrayList without using any API or other Collectionpublic class RemoveDuplicatesDemo { public static void main(String[] args) { ListUsing HashSet to remove duplicate elements from ArrayListYou can create a new HashSet by passing the List as argument. Any duplicates in the ArrayList would be discarded as HashSet stores only unique elements. Then you can add the Set again to the List after clearing the List. That gives you the List without any duplicates. Output City Name - Delhi City Name - Chennai City Name - Kolkata City Name - Mumbai City Name - BangaloreIt can be seen that duplicate elements from the ArrayList are removed but the original order is not retained. Though in most of the cases when we have such requirement to remove duplicates from the list order doesn't matter but if it does sweat not! LinkedHashSet is there to retain the order. LinkedHashSet differ from HashSet in that it maintains the insertion order. Using LinkedHashSet to remove duplicate elements from ArrayListHere is an example using LinkedHashSet to remove duplicate elements from an ArrayList, insertion order would be retained by using this option. public class RemoveDuplicatesDemo { public static void main(String[] args) { ListOutput It can be seen that the order is retained now. Removing duplicates from ArrayList using Java StreamsStream API in Java provides a very simple way to remove duplicate elements from ArrayList using the distinct method. Note that this option is available Java 8 onward. public class RemoveDuplicatesDemo { public static void main(String[] args) { ListOutput City Name - Delhi City Name - Mumbai City Name - Bangalore City Name - Chennai City Name - KolkataIt can be seen that the duplicate element is removed from the ArrayList and original order is retained too and all that is done in a single line. That's all for this topic How to Remove Duplicate Elements From an ArrayList in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks! >>>Return to Java Advanced Tutorial Page | Return to Java Collections Framework Tutorial Page>>> Related Topics
You may also like -
|