如何将集合转换为列表?

发布于 2024-07-14 05:58:35 字数 583 浏览 5 评论 0原文

我正在使用 Apache Collections 库中的 TreeBidiMap 。 我想对双精度值进行排序。

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

Collection coll = themap.values();

这自然可以正常工作。

主要问题:我现在想知道如何将(不确定哪个是正确的)coll转换/转换为List,以便它可以排序了吗?

然后,我打算迭代排序的 List 对象,该对象应该按顺序排列,并使用 TreeBidiMap (themap) 获取适当的键code>themap.getKey(iterator.next()) 其中迭代器将位于 doubles 列表上。

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 Collection of the values using:

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) coll into a List so it can be sorted?

I then intend to iterate over the sorted List object, 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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(11

凌乱心跳 2024-07-21 05:58:35
List list = new ArrayList(coll);
Collections.sort(list);

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

List list;
if (coll instanceof List)
  list = (List)coll;
else
  list = new ArrayList(coll);
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);
友谊不毕业 2024-07-21 05:58:35

像这样的东西应该可以工作,调用 ArrayList 构造函数 接受一个 Collection:

List theList = new ArrayList(coll);

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

List theList = new ArrayList(coll);
雪落纷纷 2024-07-21 05:58:35

我相信你可以这样写:

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

I believe you can write it as such:

coll.stream().collect(Collectors.toList())
掌心的温暖 2024-07-21 05:58:35

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

我的建议是:

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

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);
别靠近我心 2024-07-21 05:58:35

Java 10 引入了 List#copyOf,它返回不可修改的 List,同时保留顺序:

List<Integer> list = List.copyOf(coll);

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

List<Integer> list = List.copyOf(coll);
风吹雨成花 2024-07-21 05:58:35
Collections.sort( new ArrayList( coll ) );
Collections.sort( new ArrayList( coll ) );
掩耳倾听 2024-07-21 05:58:35

Java 8 及以上...

您可以使用 StreamsCollectors.toCollection( )

考虑以下示例映射

Map<Integer, Double> map = Map.of(
    1, 1015.45,
    2, 8956.31,
    3, 1234.86,
    4, 2348.26,
    5, 7351.03
);

到 ArrayList

List<Double> arrayList = map.values()
                            .stream()
                            .collect(
                                Collectors.toCollection(ArrayList::new)
                            );

输出:[7351.03、2348.26、1234.86、8956.31、1015.45]

到已排序的ArrayList(升序)

List<Double> arrayListSortedAsc = map.values()
                                        .stream()
                                        .sorted()
                                        .collect(
                                            Collectors.toCollection(ArrayList::new)
                                        );

输出:[1015.45、1234.86、2348.26、7351.03、8956.31]

到已排序的ArrayList(降序)

List<Double> arrayListSortedDesc = map.values()
                                        .stream()
                                        .sorted(
                                            (a, b) -> b.compareTo(a)
                                        )
                                        .collect(
                                            Collectors.toCollection(ArrayList::new)
                                        );

输出:[8956.31、7351.03、2348.26、1234.86、1015.45]

到 LinkedList

List<Double> linkedList = map.values()
                                .stream()
                                .collect(
                                    Collectors.toCollection(LinkedList::new)
                                );

输出:[7351.03、2348.26、1234.86、8956.31、1015.45]

到 HashSet

Set<Double> hashSet = map.values()
                            .stream()
                            .collect(
                                Collectors.toCollection(HashSet::new)
                            );

输出:[2348.26、8956.31、1015.45、1234.86、7351.03]

到 PriorityQueue

PriorityQueue<Double> priorityQueue = map.values()
                                            .stream()
                                            .collect(
                                                Collectors.toCollection(PriorityQueue::new)
                                            );

输出:[1015.45、1234.86、2348.26、8956.31、7351.03]

参考

Java - 包 java.util.stream

Java - 包 java.util

Java 8 onwards...

You can convert Collection to any collection (i.e, List, Set, and Queue) using Streams and Collectors.toCollection().

Consider the following example map

Map<Integer, Double> map = Map.of(
    1, 1015.45,
    2, 8956.31,
    3, 1234.86,
    4, 2348.26,
    5, 7351.03
);

to ArrayList

List<Double> arrayList = map.values()
                            .stream()
                            .collect(
                                Collectors.toCollection(ArrayList::new)
                            );

Output: [7351.03, 2348.26, 1234.86, 8956.31, 1015.45]

to Sorted ArrayList (Ascending order)

List<Double> arrayListSortedAsc = map.values()
                                        .stream()
                                        .sorted()
                                        .collect(
                                            Collectors.toCollection(ArrayList::new)
                                        );

Output: [1015.45, 1234.86, 2348.26, 7351.03, 8956.31]

to Sorted ArrayList (Descending order)

List<Double> arrayListSortedDesc = map.values()
                                        .stream()
                                        .sorted(
                                            (a, b) -> b.compareTo(a)
                                        )
                                        .collect(
                                            Collectors.toCollection(ArrayList::new)
                                        );

Output: [8956.31, 7351.03, 2348.26, 1234.86, 1015.45]

to LinkedList

List<Double> linkedList = map.values()
                                .stream()
                                .collect(
                                    Collectors.toCollection(LinkedList::new)
                                );

Output: [7351.03, 2348.26, 1234.86, 8956.31, 1015.45]

to HashSet

Set<Double> hashSet = map.values()
                            .stream()
                            .collect(
                                Collectors.toCollection(HashSet::new)
                            );

Output: [2348.26, 8956.31, 1015.45, 1234.86, 7351.03]

to PriorityQueue

PriorityQueue<Double> priorityQueue = map.values()
                                            .stream()
                                            .collect(
                                                Collectors.toCollection(PriorityQueue::new)
                                            );

Output: [1015.45, 1234.86, 2348.26, 8956.31, 7351.03]

Reference

Java - Package java.util.stream

Java - Package java.util

梦在深巷 2024-07-21 05:58:35

@Kunigami:我认为您可能对 Guava 的 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());
}

@Kunigami: I think you may be mistaken about Guava's newArrayList method. It does not check whether the Iterable is a List type and simply return the given List as-is. It always creates a new 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());
}
在风中等你 2024-07-21 05:58:35

您请求的是一个相当昂贵的操作,请确保您不需要经常执行此操作(例如在一个周期中)。

如果您需要它保持排序并且经常更新,您可以创建自定义集合。 例如,我想出了一个在引擎盖下包含 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<K> keySet() {
        return Collections.unmodifiableSet(map.keySet());
    }
    public Collection<V> values() {
        return Collections.unmodifiableCollection(multiset);
    }
    // many more methods to be implemented, e.g. count, isEmpty etc.
    // but these are fairly simple
}

这样,您就可以从 values() 返回一个已排序 Multiset。 但是,如果您需要它是一个列表(例如,您需要类似数组的 get(index) 方法),则需要更复杂的东西。

为了简洁起见,我只返回不可修改的集合。 @Lino 提到的是正确的,按原样修改 keySetvalues 集合会使其不一致。 我不知道有什么一致的方法可以使 values 可变,但是 keySet 如果使用 remove< 则可以支持 remove上面的 MyCustomCollection 类中的 /code> 方法。

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

If you need it to stay sorted and you update it frequently, you can create a custom collection. For example, I came up with one that has your TreeBidiMap and TreeMultiset under the hood. Implement only what you need and care about data integrity.

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<K> keySet() {
        return Collections.unmodifiableSet(map.keySet());
    }
    public Collection<V> values() {
        return Collections.unmodifiableCollection(multiset);
    }
    // many more methods to be implemented, e.g. count, isEmpty etc.
    // but these are fairly simple
}

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

For brevity, I only return unmodifiable collections. What @Lino mentioned is correct, and modifying the keySet or values collection as it is would make it inconsistent. I don't know any consistent way to make the values mutable, but the keySet could support remove if it uses the remove method from the MyCustomCollection class above.

絕版丫頭 2024-07-21 05:58:35

使用流:

someCollection.stream().collect(Collectors.toList())

Use streams:

someCollection.stream().collect(Collectors.toList())
非要怀念 2024-07-21 05:58:35

这是一个次优解决方案:

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

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

Collections.list(Collections.enumeration(coll));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文