简体   繁体   English

如何在 Java 中将 Set 排序为 List?

[英]How do I sort a Set to a List in Java?

In Java, I have a Set , and I want to turn it into a sorted List .在 Java 中,我有一个Set ,我想把它变成一个有序的List Is there a method in the java.util.Collections package that will do this for me? java.util.Collections包中是否有一种方法可以为我执行此操作?

The answer provided by the OP is not the best. OP提供的答案并不是最好的。 It is inefficient, as it creates a new List and an unnecessary new array.它效率低下,因为它创建了一个新的List一个不必要的新数组。 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;
}

Here's a usage example:这是一个使用示例:

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);

Sorted set:排序集:

return new TreeSet(setIWantSorted);

or:要么:

return new ArrayList(new TreeSet(setIWantSorted));

Here's how you can do it with Java 8's Streams:以下是使用 Java 8 的 Streams 实现的方法:

mySet.stream().sorted().collect(Collectors.toList());

or with a custom comparator:或使用自定义比较器:

mySet.stream().sorted(myComparator).collect(Collectors.toList());
List myList = new ArrayList(collection);
Collections.sort(myList);

… should do the trick however. ......但是应该可以解决问题。 Add flavour with Generics where applicable.在适用的情况下使用泛型添加风味。

Always safe to use either Comparator or Comparable interface to provide sorting implementation (if the object is not a String or Wrapper classes for primitive data types) .始终安全地使用 Comparator 或 Comparable 接口来提供排序实现(如果对象不是原始数据类型的 String 或 Wrapper 类)。 As an example for a comparator implementation to sort employees based on name作为比较器实现根据姓名对员工进行排序的示例

    List<Employees> empList = new LinkedList<Employees>(EmpSet);

    class EmployeeComparator implements Comparator<Employee> {

            public int compare(Employee e1, Employee e2) {
                return e1.getName().compareTo(e2.getName());
            }

        }

   Collections.sort(empList , new EmployeeComparator ());

Comparator is useful when you need to have different sorting algorithm on same object (Say emp name, emp salary, etc).当您需要对同一对象使用不同的排序算法时,比较器很有用(比如 emp 名称、emp 薪水等)。 Single mode sorting can be implemented by using Comparable interface in to the required object.可以通过使用 Comparable 接口到所需对象中来实现单模式排序。

There's no single method to do that.没有单一的方法可以做到这一点。 Use this:用这个:

@SuppressWarnings("unchecked")
public static <T extends Comparable> List<T> asSortedList(Collection<T> collection) {
  T[] array = collection.toArray(
    (T[])new Comparable[collection.size()]);
  Arrays.sort(array);
  return Arrays.asList(array);
}
TreeSet sortedset = new TreeSet();
sortedset.addAll(originalset);

list.addAll(sortedset);

where originalset = unsorted set and list = the list to be returned其中 originalset = unsorted set 和 list = 要返回的列表

You can convert a set into an ArrayList , where you can sort the ArrayList using Collections.sort(List) .您可以将集合转换为ArrayList ,您可以在其中使用Collections.sort(List)ArrayList进行排序。

Here is the code:这是代码:

keySet = (Set) map.keySet();
ArrayList list = new ArrayList(keySet);     
Collections.sort(list);

@Jeremy Stein I wanted to implement same code. @Jeremy Stein 我想实现相同的代码。 As well I wanted to sort the set to list, So instead of using Set I converted set values into List and sort that list by it's one the variable.同样,我想将集合排序到列表中,因此我没有使用 Set 我将集合值转换为 List 并通过它的一个变量对该列表进行排序。 This code helped me,这段代码帮助了我,

set.stream().sorted(Comparator.comparing(ModelClassName::sortingVariableName)).collect(Collectors.toList());

I am using this code, which I find more practical than the accepted answer above:我正在使用此代码,我发现它比上面接受的答案更实用:

List<Thing> thingList = new ArrayList<>(thingSet);
thingList.sort((thing1, thing2) -> thing1.getName().compareToIgnoreCase(thing2.getName()));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM