Java list double sort

Java 8 Comparator — How to sort a List

In this article, we’re going to see several examples on how to sort a List in Java 8.

1. Sort a List of String alphabetically

ListString> cities = Arrays.asList( "Milan", "london", "San Francisco", "Tokyo", "New Delhi" ); System.out.println(cities); //[Milan, london, San Francisco, Tokyo, New Delhi] cities.sort(String.CASE_INSENSITIVE_ORDER); System.out.println(cities); //[london, Milan, New Delhi, San Francisco, Tokyo] cities.sort(Comparator.naturalOrder()); System.out.println(cities); //[Milan, New Delhi, San Francisco, Tokyo, london]

By purpose, we’ve written London with ‘L’ in low-case to better highlight difference between Comparator.naturalOrder() that returns a Comparator that sorts by placing capital letters first and String.CASE_INSENSITIVE_ORDER that returns a case-insensitive Comparator .

Basically, in Java 7 we were using Collections.sort() that was accepting a List and, eventually, a Comparator — in Java 8 we have the new List.sort() that accepts a Comparator .

2. Sort a List of Integer

ListInteger> numbers = Arrays.asList(6, 2, 1, 4, 9); System.out.println(numbers); //[6, 2, 1, 4, 9] numbers.sort(Comparator.naturalOrder()); System.out.println(numbers); //[1, 2, 4, 6, 9]

3. Sort a List by String field

Let’s suppose we’ve our Movie class and we want to sort our List by title. We can use Comparator.comparing() and pass a function that extracts the field to use for sorting — title — in this example.

ListMovie> movies = Arrays.asList( new Movie("Lord of the rings"), new Movie("Back to the future"), new Movie("Carlito's way"), new Movie("Pulp fiction")); movies.sort(Comparator.comparing(Movie::getTitle)); movies.forEach(System.out::println);
Movietitle='Back to the future'> Movietitle='Carlito's way'> Movietitle='Lord of the rings'> Movietitle='Pulp fiction'>

As you’ve probably noticed we haven’t passed any Comparator but the List is correctly sorted. That’s because of the title — the extracted field — that is a String and String implements Comparable interface. If you peek at Comparator.comparing() implementation you will see that it calls compareTo on the extracted key.

4. Sort a List by double field

In a similar way, we can use Comparator.comparingDouble() for comparing double value. In the example, we want to order our List of Movie by rating, from the highest to the lowest.

ListMovie> movies = Arrays.asList( new Movie("Lord of the rings", 8.8), new Movie("Back to the future", 8.5), new Movie("Carlito's way", 7.9), new Movie("Pulp fiction", 8.9)); movies.sort(Comparator.comparingDouble(Movie::getRating) .reversed()); movies.forEach(System.out::println);

We used reversed function on the Comparator in order to invert default natural-order that is from lowest to highest. Comparator.comparingDouble() uses Double.compare() under the hood.

If you need to compare int or long you can use comparingInt() and comparingLong() respectively.

5. Sort a List with custom Comparator

In the previous examples we haven’t specified any Comparator since it wasn’t necessary but let’s see an example in which we define our own Comparator . Our Movie class has a new field — starred — set using the third constructor parameter. In the example, we want to sort the list so that we have starred movie at the top of the List .

ListMovie> movies = Arrays.asList( new Movie("Lord of the rings", 8.8, true), new Movie("Back to the future", 8.5, false), new Movie("Carlito's way", 7.9, true), new Movie("Pulp fiction", 8.9, false)); movies.sort(new ComparatorMovie>()  @Override public int compare(Movie m1, Movie m2)  if(m1.getStarred() == m2.getStarred()) return 0; > return m1.getStarred() ? -1 : 1; > >); movies.forEach(System.out::println);
Moviestarred=true, title='Lord of the rings', rating=8.8> Moviestarred=true, title='Carlito's way', rating=7.9> Moviestarred=false, title='Back to the future', rating=8.5> Moviestarred=false, title='Pulp fiction', rating=8.9>

We can, of course, use Lambda expression instead of Anonymous class as follows:

movies.sort((m1, m2) ->  if(m1.getStarred() == m2.getStarred()) return 0; > return m1.getStarred() ? -1 : 1; >);

And we can also use again Comparator.comparing() :

movies.sort(Comparator.comparing(Movie::getStarred, (star1, star2) ->  if(star1 == star2) return 0; > return star1 ? -1 : 1; >));

In the latest example Comparator.comparing() takes as first parameter the function to extract the key to use for sorting and a Comparator as second parameter. This Comparator uses the extracted keys for comparison, star1 and star2 are indeed boolean and represents m1.getStarred() and m2.getStarred() respectively.

6. Sort a List with chain of Comparator

In the latest example, we want to have starred movie at the top and then sort by rating.

ListMovie> movies = Arrays.asList( new Movie("Lord of the rings", 8.8, true), new Movie("Back to the future", 8.5, false), new Movie("Carlito's way", 7.9, true), new Movie("Pulp fiction", 8.9, false)); movies.sort(Comparator.comparing(Movie::getStarred) .reversed() .thenComparing(Comparator.comparing(Movie::getRating) .reversed()) ); movies.forEach(System.out::println);
Moviestarred=true, title='Lord of the rings', rating=8.8> Moviestarred=true, title='Carlito's way', rating=7.9> Moviestarred=false, title='Pulp fiction', rating=8.9> Moviestarred=false, title='Back to the future', rating=8.5>

As you’ve seen we first sort by starred and then by rating — both reversed since we want the highest value and true first.

Reverse Coding

Traditionally teaching methods first start with theory and then move to practice. I prefer do the opposite, I find it more effective. I prefer to start from a real example, to play with that, to break it down, to ask my self some questions and only then to move to the theory. Reversecoding.net follows this approach: hope you’ll find it helpful. Thanks for visiting!

Источник

Java Arrays — sort(double[] a) Method

The Java Arrays sort(double[] a) method sorts the specified array of doubles into ascending numerical order. This method using a Dual-Pivot Quicksort algorithm which breaks the array into subarrays, sorted them and then merged to give a sorted array.

Declaration

Following is the declaration for java.util.Arrays.sort(double[] a) method

public static void sort(double[] a)

Parameters

a − This is the array to be sorted.

Return Value

This method does not return any value.

Exception

Java Arrays sort​(double[] a, int fromIndex, int toIndex) Method

Description

The Java Arrays sort(double[] a, int fromIndex, int toIndex) method sorts the specified range of given array of doubles into ascending numerical order. This method using a Dual-Pivot Quicksort algorithm which breaks the array into subarrays, sorted them and then merged to give a sorted array.

Declaration

Following is the declaration for java.util.Arrays.sort(double[] a, int fromIndex, int toIndex) method

public static void sort​(double[] a, int fromIndex, int toIndex)

Parameters

  • a − This is the array to be sorted.
  • fromIndex − This is the index of the first element, inclusive, to be sorted.
  • toIndex − This is the index of the last element, exclusive, to be sorted

Return Value

This method is not returning anything.

Exception

  • IllegalArgumentException − if fromIndex > toIndex
  • ArrayIndexOutOfBoundsException − if fromIndex < 0 or toIndex >array.length

Example 1

The following example shows the usage of Java Arrays sort(double[]) method. First, we’ve created an array of doubles, printed the original array. Using sort() method, array is sorted and printed thereafter.

package com.tutorialspoint; import java.util.Arrays; public class ArrayDemo < public static void main(String[] args) < // initialize unsorted array double arr[] = < 11.0, 54.0, 23.0, 32.0, 15.0, 24.0, 31.0, 12.0 >; System.out.print("Original Array: ["); // print the array for (int i = 0; i < arr.length; i++) < System.out.print(arr[i] + " "); >System.out.println("]"); // sort the array Arrays.sort(arr); System.out.print("Sorted Array: ["); // print the array for (int i = 0; i < arr.length; i++) < System.out.print(arr[i] + " "); >System.out.println("]"); > >

Output

Let us compile and run the above program, this will produce the following result −

Original Array: [11.0 54.0 23.0 32.0 15.0 24.0 31.0 12.0 ] Sorted Array: [11.0 12.0 15.0 23.0 24.0 31.0 32.0 54.0 ]

Example 2

The following example shows the usage of Java Arrays sort(double[], int, int) method. First, we’ve created an array of doubles, printed the original array. Using sort() method, array is sorted and printed thereafter.

package com.tutorialspoint; import java.util.Arrays; public class ArrayDemo < public static void main(String[] args) < // initialize unsorted array double arr[] = < 11.0, 54.0, 23.0, 32.0, 15.0, 24.0, 31.0, 12.0 >; System.out.print("Original Array: ["); // print the array for (int i = 0; i < arr.length; i++) < System.out.print(arr[i] + " "); >System.out.println("]"); // sort the array Arrays.sort(arr, 0, arr.length); System.out.print("Sorted Array: ["); // print the array for (int i = 0; i < arr.length; i++) < System.out.print(arr[i] + " "); >System.out.println("]"); > >

Output

Let us compile and run the above program, this will produce the following result −

Original Array: [11.0 54.0 23.0 32.0 15.0 24.0 31.0 12.0 ] Sorted Array: [11.0 12.0 15.0 23.0 24.0 31.0 32.0 54.0 ]

Example 3

The following example shows the usage of Java Arrays sort(double[], int, int) method. First, we’ve created an array of doubles, printed the original array. Using sort() method, a sub-array is sorted and printed thereafter.

package com.tutorialspoint; import java.util.Arrays; public class ArrayDemo < public static void main(String[] args) < // initialize unsorted array double arr[] = < 11.0, 54.0, 23.0, 32.0, 15.0, 24.0, 31.0, 12.0 >; System.out.print("Original Array: ["); // print the array for (int i = 0; i < arr.length; i++) < System.out.print(arr[i] + " "); >System.out.println("]"); // sort first five elements of the array Arrays.sort(arr, 0, 5); System.out.print("Sorted Array: ["); // print the array for (int i = 0; i < arr.length; i++) < System.out.print(arr[i] + " "); >System.out.println("]"); > >

Output

Let us compile and run the above program, this will produce the following result −

Original Array: [11.0 54.0 23.0 32.0 15.0 24.0 31.0 12.0 ] Sorted Array: [11.0 15.0 23.0 32.0 54.0 24.0 31.0 12.0 ]

Источник

Sort a Double LinkedList in Java

This code is for showing how to sort a Double LinkedList in Java. You can use sort(List list) method. It will sort the double list in ascending order. If you want to sort it in descending order, you can use sort(List list, Comparator c) .

public static void main(String[] args) { LinkedListDouble> doubleList = new LinkedListDouble>(); doubleList.add(2.2); doubleList.add(1.1); doubleList.add(3.3); System.out.println(doubleList); //sort in ascending order Collections.sort(doubleList); System.out.println(doubleList); //sort in descending order Collections.sort(doubleList, Collections.reverseOrder()); System.out.println(doubleList); }

public static void main(String[] args) < LinkedListdoubleList = new LinkedList(); doubleList.add(2.2); doubleList.add(1.1); doubleList.add(3.3); System.out.println(doubleList); //sort in ascending order Collections.sort(doubleList); System.out.println(doubleList); //sort in descending order Collections.sort(doubleList, Collections.reverseOrder()); System.out.println(doubleList); >

If you want someone to read your code, please put the code inside

 and 

tags. For example:

let we have a linklist of size n stored info are name and id what is the best way to sort ? job interview

Источник

Java list double sort

Learn Latest Tutorials

Splunk tutorial

SPSS tutorial

Swagger tutorial

T-SQL tutorial

Tumblr tutorial

React tutorial

Regex tutorial

Reinforcement learning tutorial

R Programming tutorial

RxJS tutorial

React Native tutorial

Python Design Patterns

Python Pillow tutorial

Python Turtle tutorial

Keras tutorial

Preparation

Aptitude

Logical Reasoning

Verbal Ability

Company Interview Questions

Artificial Intelligence

AWS Tutorial

Selenium tutorial

Cloud Computing

Hadoop tutorial

ReactJS Tutorial

Data Science Tutorial

Angular 7 Tutorial

Blockchain Tutorial

Git Tutorial

Machine Learning Tutorial

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures tutorial

DAA tutorial

Operating System

Computer Network tutorial

Compiler Design tutorial

Computer Organization and Architecture

Discrete Mathematics Tutorial

Ethical Hacking

Computer Graphics Tutorial

Software Engineering

html tutorial

Cyber Security tutorial

Automata Tutorial

C Language tutorial

C++ tutorial

Java tutorial

.Net Framework tutorial

Python tutorial

List of Programs

Control Systems tutorial

Data Mining Tutorial

Data Warehouse Tutorial

Javatpoint Services

JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.

  • Website Designing
  • Website Development
  • Java Development
  • PHP Development
  • WordPress
  • Graphic Designing
  • Logo
  • Digital Marketing
  • On Page and Off Page SEO
  • PPC
  • Content Development
  • Corporate Training
  • Classroom and Online Training
  • Data Entry

Training For College Campus

JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week

Like/Subscribe us for latest updates or newsletter RSS Feed Subscribe to Get Email Alerts Facebook Page Twitter Page YouTube Blog Page

Источник

Читайте также:  Добавление картинки
Оцените статью