如何在Java中将一个集合排序到列表? [英] How do I sort a Set to a List in Java?

查看:189
本文介绍了如何在Java中将一个集合排序到列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中,我有一个 Set ,我想把它变成一个排序 List 。在 java.util.Collections 包中有一个方法会为我这样做?

In Java, I have a Set, and I want to turn it into a sorted List. Is there a method in the java.util.Collections package that will do this for me?

推荐答案

答案由OP 不是最好的。它效率低下,因为它创建了一个新的 List 一个不必要的新数组。

The answer provided by the OP is not the best. It is inefficient, as it creates a new List and an unnecessary new array. Also, it raises "unchecked" warnings because of the type safety issues around generic arrays.

而是使用类似这样的:

public static
<T extends Comparable<? super T>> List<T> asSortedList(Collection<T> c) {
  List<T> list = new ArrayList<T>(c);
  java.util.Collections.sort(list);
  return list;
}

这里有一个用法示例:

Map<Integer, String> map = new HashMap<Integer, String>();
/* Add entries to the map. */
...
/* Now get a sorted list of the *values* in the map. */
Collection<String> unsorted = map.values();
List<String> sorted = Util.asSortedList(unsorted);

这篇关于如何在Java中将一个集合排序到列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆