How to sort list in java
How to sort list in java
Java sort list
last modified July 15, 2022
Java sort list tutorial shows how to sort lists in Java.
Sorting
Sorting is arranging elements in an ordered sequence. Over the years, several algorithms were developed to perform sorting on data; for instance merge sort, quick sort, selection sort, or bubble sort. (Another meaning of sorting is categorizing: grouping elements with similar properties.)
The opposite of sorting, rearranging a sequence of elements in a random or meaningless order, is called shuffling.
Data can be sorted alphabetically or numerically. The sort key specifies the criteria used to do the sorting. It is possible to sort objects by multiple keys. For instance, when sorting users, the names of the users could be used as primary sort key, and their salary as the secondary sort key.
Sorting order
A standard order is called the ascending order: a to z, 0 to 9. The reverse order is called the descending order: z to a, 9 to 0. For dates and times, ascending means that earlier values precede later ones e.g. 5/5/2020 will sort ahead of 11/11/2021.
Stable sort
A stable sort is one where the initial order of equal elements is preserved. Some sorting algorithms are naturally stable, some are unstable. For instance, the merge sort and the bubble sort are stable sorting algorithms. On the other hand, heap sort and quick sort are examples of unstable sorting algorithms.
Java internally uses a stable sort algorithms.
Java sort methods
In Java, we can sort a list in-place or we can return a new sorted list.
Java sort list of integers
In the following example, we sort a list of integers.
The integers are sorted in ascending and descending orders. The data is sorted in-place; i.e. the original list is modified.
In the next example, we do not modify the original source of data.
Java sort list of strings
The following example sorts strings.
Java case insensitive list sort
In the following example, we show how to sort strings in case-insensitive order.
We sort a list of words in-place in natural order and later regardless of case.
Java sort list of names by surname
The following example sorts full names by surname.
We have a list of names. We wort the names by surnames, in reverse order. By default, they would be sorted by first names, because they preced surnames.
We create a Function which is a key extractor. It extracts the surnmaes from the strings.
We pass the function to the Comparator.comparing method.
Java sort list by fields
We are going to sort a list of objects by their fields.
We have a list of cars. We sort the cars by their price and later by their name.
Java sort list by multiple fields
The next example shows how to sort objects by multiple fields.
The list of persons is sorted by age and then by name.
Java sort list with custom comparator
We sort a list of objects by defining an external comparator object.
A deck of cards is sorted first by rank and in case of equal rank by suit.
We define an external comparator, which implements the Comparator interface and defines the compare method.
Java sort list with a Comparable object
Now we use Comparable interface to sort objects.
The Comparable interface defines an internal compareTo sorting method.
Java sort list final example
The final example summarizes several sorting techniques.
We parse a multiline string to form a list of users. Then we sort the list by date of birth, last name, occupation, and occupation and reversed date of birth.
In this article, we have sorted lists in Java.
How to Sort a List in Java
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
Sometimes we have to sort a list in Java before processing its elements. In this tutorial, we will learn how to sort a list in the natural order. We will also learn how to use our own Comparator implementation to sort a list of objects. Java List is similar to arrays except that the length of the list is dynamic and it comes in Java Collection framework. Actually, List is an interface and most of the time we use one of its implementation like ArrayList or LinkedList etc.
Java Sort List
Here we will learn how to sort a list of Objects in Java. We can use Collections.sort() method to sort a list in the natural ascending order. All the elements in the list must implement Comparable interface, otherwise IllegalArgumentException is thrown. Let’s look at a quick example to sort a list of strings.
As you can see that we are using Collections.sort() method to sort the list of Strings. The String class implements Comparable interface. Output:
Java Sort List
Java Sort List of Objects
Let’s see another example where we will sort a list of custom objects. Note that the class must implement Comparable interface.
Sort a List in Java using Comparator
Collections.sort() method is overloaded and we can also provide our own Comparator implementation for sorting rules. Since Comparator is a functional interface, we can use lambda expressions to write its implementation in a single line.
Summary
Collections class sort() method is used to sort a list in Java. We can sort a list in natural ordering where the list elements must implement Comparable interface. We can also pass a Comparator implementation to define the sorting rules.
You can checkout more examples from our GitHub Repository.
Want to learn more? Join the DigitalOcean Community!
Join our DigitalOcean community of over a million developers for free! Get help and share knowledge in our Questions & Answers section, find tutorials and tools that will help you grow as a developer and scale your project or business, and subscribe to topics of interest.
How to sort List of objects by some property
I have simple class
16 Answers 16
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
EDIT: Sample implementation:
For Example:
With Java 8 onwards, you can simply use lambda expression to represent Comparator instance.
JAVA 8 and Above Answer (Using Lambda Expressions)
In Java 8, Lambda expressions were introduced to make this even easier! Instead of creating a Comparator() object with all of it’s scaffolding, you can simplify it as follows: (Using your object as an example)
or even shorter:
That one statement is equivalent to the following:
Think of Lambda expressions as only requiring you to put in the relevant parts of the code: the method signature and what gets returned.
One last note: It is easy to compare ‘long’ or ‘int’ primitives, you can just subtract one from the other. If you are comparing objects (‘Long’ or ‘String’), I suggest you use their built-in comparison. Example:
How to sort a List/ArrayList?
I have a List of doubles in java and I want to sort ArrayList in descending order.
Input ArrayList is as below:
The out put should be like this
21 Answers 21
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
That will do what you want. Remember to import Collections though!
For your example, this will do the magic in Java 8
But if you want to sort by some of the fields of the object you are sorting, you can do it easily by:
Use util method of java.util.Collections class, i.e
In fact, if you want to sort custom object you can use
see collections api
Using lambdas (Java8), and stripping it down to the barest of syntax (the JVM will infer plenty in this case), you get:
A more verbose version:
With Java8 there is a default sort method on the List interface that will allow you to sort the collection if you provide a Comparator. You can easily sort the example in the question as follows:
Note: the args in the lambda are swapped when passed in to Double.compare to ensure the sort is descending
You can use Collections.sort(list) to sort list if your list contains Comparable elements. Otherwise I would recommend you to implement that interface like here:
and of course provide your own realization of compareTo method like here:
And then you can again use Colection.sort(list) as now list contains objects of Comparable type and can be sorted. Order depends on compareTo method. Check this https://docs.oracle.com/javase/tutorial/collections/interfaces/order.html for more detailed information.
Here is a short cheatsheet that covers typical cases:
Collections.sort allows you to pass an instance of a Comparator which defines the sorting logic. So instead of sorting the list in natural order and then reversing it, one can simply pass Collections.reverseOrder() to sort in order to sort the list in reverse order:
As mentioned by @Marco13, apart from being more idiomatic (and possibly more efficient), using the reverse order comparator makes sure that the sort is stable (meaning that the order of elements will not be changed when they are equal according to the comparator, whereas reversing will change the order)
You can do like this:
Collection has a default Comparator that can help you with that.
Also, if you want to use some Java 8 new features, you can do like that:
if you are using Java SE 8, then this might be of help.
How to sort an ArrayList
All I need is the simplest method of sorting an ArrayList that does not use the in-built Java sorter. Currently I change my ArrayList to an Array and use a liner sorting code, but I later need to call on some elements and ArrayLists are easier to do that.
9 Answers 9
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
you can use anonymous sort.
where T is the type you want to sort (i.e String, Objects) and simply implement the Comparator interface to your own needs
Easiest (but I’m guessing this is what you’re saying you can’t use):
Next easiest (but a waste):
Assuming «in-built sort» refers to Collections.sort() and you are fine with the sorting algorithm you have implemented, you can just convert your sorted array into an ArrayList
Alternatively, you can rewrite your sorting algorithm to work with a List (such as an ArrayList) instead of an array by using the get(int index) and set(int index, E element) methods.
Sorting Arguments passed through Command prompt; without using Arrays.sort
By using Array.sort
If i remember correctly when you pull an element out of the middle of an arrayList it moves the rest of the elements down automaticly. If you do a loop that looks for the lowest value and pull it out then place it at the end of the arrayList. On each pass i— for the index. That is use one less. So on a 10 element list you will look at all 10 elements take the lowest one and append it to the end. Then you will look at the first nine and take the lowest of it out and append it to the end. Then the first 8 and so on till the list is sorted.
Check for Comparator in java. You can implement your own sorting using this and use Collections.sort(..) to sort the arraylist using your own Comparator
If you are meant to sort the array yourself, then one of the simplest algorithms is bubble sort. This works by making multiple passes through the array, comparing adjacent pairs of elements, and swapping them if the left one is larger than the right one.
Since this is homework, I’ll leave it to you to figure out the rest. Start by visualizing your algorithm, then think about how many passes your algorithm needs to make, and where it needs to start each pass. Then code it.
You also need to understand and solve the problem of how you compare a pair of array elements: