Reputation: 1139
I am getting the unique elements from a arraylist into a hashset but it is being sorted by itself.But i need the data not to be in sorted order.How can it be done?
Upvotes: 3
Views: 3351
Reputation: 3522
What do yo mean by 'I want data not in sorted order'? Do you mean to say that you want the same order in which it is present in the list? If so, you can create a LinkedHashSet and add the entries from the arraylist.
eg:
ArrayList list = new ArrayList();
LinkedHashSet set = new LinkedHashSet();
for (String temp : list) {
set.add(temp);
}
This will ensure the same order in which the elements are present in the arraylist.
Upvotes: 0
Reputation: 1108712
HashSet getting sorted
The items of a HashSet
is not in a particular order at all, as explicitly stated in its javadoc:
It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time.
Perhaps you meant to say that the items are "rearranged" in a different order than you have added the items and that this is undesireable.
In that case, just use LinkedHashSet
instead of HashSet
. It maintains the elements in insertion order.
Set<T> unique = new LinkedHashSet<T>(arrayList);
Or, perhaps, if you prefer automatic ordering based on the element's Comparable#compareTo()
implementation or would like to supply a custom Comparator
, then use a TreeSet
instead.
Set<T> uniqueAndSorted = new TreeSet<T>(arrayList);
Upvotes: 5