How do I sort a Set to a List in Java?

JavaSortingCollections

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

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

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

Solution 2 - Java

Sorted set:

return new TreeSet(setIWantSorted);

or:

return new ArrayList(new TreeSet(setIWantSorted));

Solution 3 - Java

Here's how you can do it with Java 8's Streams:

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

or with a custom comparator:

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

Solution 4 - Java

List myList = new ArrayList(collection);
Collections.sort(myList);

… should do the trick however. Add flavour with Generics where applicable.

Solution 5 - Java

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) . 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). Single mode sorting can be implemented by using Comparable interface in to the required object.

Solution 6 - Java

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

Solution 7 - Java

You can convert a set into an ArrayList, where you can sort the ArrayList using Collections.sort(List).

Here is the code:

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

Solution 8 - Java

TreeSet sortedset = new TreeSet();
sortedset.addAll(originalset);

list.addAll(sortedset);

where originalset = unsorted set and list = the list to be returned

Solution 9 - Java

@Jeremy Stein I wanted to implement same code. 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. This code helped me,

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

Solution 10 - Java

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJeremy SteinView Question on Stackoverflow
Solution 1 - JavaericksonView Answer on Stackoverflow
Solution 2 - JavaSteve B.View Answer on Stackoverflow
Solution 3 - JavanschumView Answer on Stackoverflow
Solution 4 - JavaEskoView Answer on Stackoverflow
Solution 5 - JavaSatheesh CheveriView Answer on Stackoverflow
Solution 6 - JavaJeremy SteinView Answer on Stackoverflow
Solution 7 - JavaAmitView Answer on Stackoverflow
Solution 8 - JavaSujith MohanView Answer on Stackoverflow
Solution 9 - JavaDeepak KumbharView Answer on Stackoverflow
Solution 10 - Javann4lView Answer on Stackoverflow