Converting a TreeSet to ArrayList?

前端 未结 3 1675
花落未央
花落未央 2020-12-17 08:52

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

相关标签:
3条回答
  • 2020-12-17 09:14

    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);
    
    0 讨论(0)
  • 2020-12-17 09:25

    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);
    
    0 讨论(0)
  • 2020-12-17 09:38

    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();
    
    0 讨论(0)
提交回复
热议问题