Java 如何将集合转换为列表?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/580160/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 16:29:07  来源:igfitidea点击:

How to convert a Collection to List?

javalistsortingcollectionsapache-commons-collection

提问by Ankur

I am using TreeBidiMapfrom the Apache Collectionslibrary. I want to sort this on the values which are doubles.

我使用TreeBidiMap来自Apache的集合库。我想根据doubles.

My method is to retrieve a Collectionof the values using:

我的方法是Collection使用以下方法检索一个值:

Collection coll = themap.values();

Which naturally works fine.

这自然很好用。

Main Question:I now want to know how I can convert/cast (not sure which is correct) collinto a Listso it can be sorted?

主要问题:我现在想知道如何将(不确定哪个是正确的)转换/转换coll为 aList以便对其进行排序?

I then intend to iterate over the sorted Listobject, which should be in order and get the appropriate keys from the TreeBidiMap(themap) using themap.getKey(iterator.next())where the iterator will be over the list of doubles.

然后我打算遍历排序的List对象,这应该是为了,并从相应的键TreeBidiMapthemap使用),themap.getKey(iterator.next())其中,迭代器都将超过列表doubles

采纳答案by Paul Tomblin

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.

正如 Erel Segal Halevi 在下面所说的,如果 coll 已经是一个列表,你可以跳过第一步。但这将取决于 TreeBidiMap 的内部结构。

List list;
if (coll instanceof List)
  list = (List)coll;
else
  list = new ArrayList(coll);

回答by Hyman Leow

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

这样的事情应该可以工作,调用带有集合的ArrayList 构造函数

List theList = new ArrayList(coll);

回答by OscarRyz

Collections.sort( new ArrayList( coll ) );

回答by Erel Segal-Halevi

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.

我认为 Paul Tomblin 的回答可能在 coll 已经是一个列表的情况下是浪费的,因为它会创建一个新列表并复制所有元素。如果 coll 包含许多元素,这可能需要很长时间。

My suggestion is:

我的建议是:

List list;
if (coll instanceof List)
  list = (List)coll;
else
  list = new ArrayList(coll);
Collections.sort(list);

回答by Nathan Perrier

@Kunigami: I think you may be mistaken about Guava's newArrayListmethod. It does not check whether the Iterable is a List type and simply return the given List as-is. It alwayscreates a new list:

@Kunigami:我想你可能对番石榴的newArrayList方法有误解。它不检查 Iterable 是否是 List 类型,而只是按原样返回给定的 List。它总是创建一个新列表:

@GwtCompatible(serializable = true)
public static <E> ArrayList<E> newArrayList(Iterable<? extends E> elements) {
  checkNotNull(elements); // for GWT
  // Let ArrayList's sizing logic work, if possible
  return (elements instanceof Collection)
      ? new ArrayList<E>(Collections2.cast(elements))
      : newArrayList(elements.iterator());
}

回答by Arhus

Here is a sub-optimal solution as a one-liner:

这是作为单行的次优解决方案:

Collections.list(Collections.enumeration(coll));

回答by Vlasec

What you request is quite a costy operation, make sure you don't need to do it often (e.g in a cycle).

您要求的操作成本很高,请确保您不需要经常执行此操作(例如在一个循环中)。

Otherwise, you can create a custom collection. I came up with one that has your TreeBidiMapand TreeMultisetunder the hood. Implement only what you need and care about data integrity.

否则,您可以创建自定义集合。我想出了一个有你的TreeBidiMapTreeMultiset引擎盖下的。仅实施您需要并关心数据完整性的内容。

class MyCustomCollection implements Map<K, V> {
    TreeBidiMap<K, V> map;
    TreeMultiset<V> multiset;
    public V put(K key, V value) {
        removeValue(map.put(key, value));
        multiset.add(value);
    }
    public boolean remove(K key) {
        removeValue(map.remove(key));
    }
    /** removes value that was removed/replaced in map */
    private removeValue(V value) {
        if (value != null) {
            multiset.remove(value);
        }
    }
    public Set keySet() {
        return map.keySet();
    }
    public Multiset values() {
        return multiset;
    }
    // many more methods to be implemented, e.g. count, isEmpty etc.
}

This way, you have a sortedMultisetreturned from values(). However, if you need it to be a list (e.g. you need the array-like get(index)method), you'd have to invent something more complex.

这样一来,你有一个排序Multiset从返回values()。然而,如果你需要它是一个列表(例如你需要类似数组的get(index)方法),你就必须发明一些更复杂的东西。

回答by Eyal Ofri

I believe you can write it as such:

我相信你可以这样写:

coll.stream().collect(Collectors.toList())