Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List to Set without affecting the order of the elements

I have a List of Strings as ["abc", "xyz", "abc", "mno", "123"]

now I want the unique values out of this list. To do that I am converting the List to HashSet.

I am able to achieve the same but the order of elements is affected. The output is very random, one of the result is ["123", "xyz", "abc", "mno"].

But I want resulted set containing the items in the same order as the arraylist. How can I achieve this?

List<String> parameters = new ArrayList<String>();
//add the parameter to List
Set<String> parameterSet=new HashSet<String>(parameters);
like image 241
Seeker Avatar asked Dec 01 '22 17:12

Seeker


1 Answers

Use LinkedHashSet

List<String> parameters = new ArrayList<String>();

                                            Call the List here
                                                     |
Set<String> parameterSet=new LinkedHashSet<String>(parameters);
like image 117
Masudul Avatar answered Dec 26 '22 22:12

Masudul