How to convert a Collection to List?

前端 未结 10 537
不知归路
不知归路 2020-12-07 09:04

I am using TreeBidiMap from the Apache Collections library. I want to sort this on the values which are doubles.

My method is to retrieve a

相关标签:
10条回答
  • 2020-12-07 09:12

    Something like this should work, calling the ArrayList constructor that takes a Collection:

    List theList = new ArrayList(coll);
    
    0 讨论(0)
  • 2020-12-07 09:16

    I think Paul Tomblin's answer may be wasteful in case coll is already a list, because it will create a new list and copy all elements. If coll contains many elemeents, this may take a long time.

    My suggestion is:

    List list;
    if (coll instanceof List)
      list = (List)coll;
    else
      list = new ArrayList(coll);
    Collections.sort(list);
    
    0 讨论(0)
  • 2020-12-07 09:16

    Java 10 introduced List#copyOf which returns unmodifiable List while preserving the order:

    List<Integer> list = List.copyOf(coll);
    
    0 讨论(0)
  • 2020-12-07 09:18
    List list = new ArrayList(coll);
    Collections.sort(list);
    

    As Erel Segal Halevi says below, if coll is already a list, you can skip step one. But that would depend on the internals of TreeBidiMap.

    List list;
    if (coll instanceof List)
      list = (List)coll;
    else
      list = new ArrayList(coll);
    
    0 讨论(0)
  • 2020-12-07 09:19

    I believe you can write it as such:

    coll.stream().collect(Collectors.toList())
    
    0 讨论(0)
  • 2020-12-07 09:24

    Use streams:

    someCollection.stream().collect(Collectors.toList())
    
    0 讨论(0)
提交回复
热议问题