I read data from a text file, so there may be:
John Mary John Leeds
I now need to get 3 unique elements in the ArrayList, because there are only 3 unique values in the file output (as above).
I can use a HashTable and add information to it, then simply copy its data into the List. Are there other solutions?
1) First split the string using String split() method and assign the substrings into an array of strings. We can split the string based on any character, expression etc. 2) Create an ArrayList and copy the element of string array to newly created ArrayList using Arrays. asList() method.
We'll use the distinct() method from the Stream API, which returns a stream consisting of distinct elements based on the result returned by the equals() method. There we have it, three quick ways to clean up all the duplicate items from a List.
Why do you need to store it in a List
? Do you actually require the data to be ordered or support index-based look-ups?
I would suggest storing the data in a Set
. If ordering is unimportant you should use HashSet
. However, if you wish to preserve ordering you could use LinkedHashSet
.
If you have a List
containing duplicates, and you want a List
without, you could do:
List<String> newList = new ArrayList<String>(new HashSet<String>(oldList));
That is, wrap the old list into a set to remove duplicates and wrap that set in a list again.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With