31

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 ?

James A Mohler
  • 11,060
  • 15
  • 46
  • 72
priyank
  • 4,634
  • 11
  • 45
  • 52

3 Answers3

69

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);
Sadeq Dousti
  • 3,346
  • 6
  • 35
  • 53
yegor256
  • 102,010
  • 123
  • 446
  • 597
5

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);
Perception
  • 79,279
  • 19
  • 185
  • 195
1

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();
koppor
  • 19,079
  • 15
  • 119
  • 161