I have a TreeSet which contains > 100k objects. I have another method which requires ArrayList as an param.
Is there any way I can accomplish this without iterating whole TreeSet and then adding each object manually to ArrayList ?
I have a TreeSet which contains > 100k objects. I have another method which requires ArrayList as an param.
Is there any way I can accomplish this without iterating whole TreeSet and then adding each object manually to ArrayList ?
How about this:
new ArrayList<T>(set);
For Java 7 and later, this can be simplified, as type arguments <T>
can be replaced with diamond type <>
:
new ArrayList<>(set);
ArrayList has a convenience method addAll
that fits the bill nicely:
final Set<Object> set = ...
List<Object> list = new ArrayList<Object>(someBigNum);
list.addAll(set);
In case one uses Eclipse Collections, which has super-powers and is developed by Goldman Sachs, there is toList()
:
MutableSortedSet<Object> set = SortedSets.mutable.empty();
...
return set.toList();
Providing a comparator is also possible:
MutableSortedSet<Object> set = SortedSets.mutable.of(comparator);
...
return set.toList();