如何在 Java 中将 Set 排序为 List? [英] How do I sort a Set to a List in Java?

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

问题描述

在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.

相反,请使用以下内容:

Instead, use something like this:

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 中将 Set 排序为 List?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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