Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save a list of unique Strings in the ArrayList

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?

like image 639
EugeneP Avatar asked Feb 10 '10 08:02

EugeneP


People also ask

Can we store string in ArrayList?

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.

How do you make a list distinct in Java?

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.


2 Answers

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.

like image 200
Adamski Avatar answered Oct 04 '22 12:10

Adamski


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.

like image 41
Fabian Steeg Avatar answered Oct 04 '22 12:10

Fabian Steeg