TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

<< Back to JAVA

Java Sort Examples: Arrays.sort, Comparable

Sort elements in arrays and other collections. Use Arrays.sort and the Comparable interface.
Sort. You see 3 tiles on a table. One is light, one is dark and the third is in between. To sort them you order them based on lightness. The cavern has many secrets.
In Java programs Array.sort arranges elements in place. By default, sort() uses an ascending order. With objects, we use the Comparable interface, and implement its compareTo method.
A Comparable example. Here we introduce a custom class, Item, and have it implement Comparable(Item). It specifies the compareTo method. In compareTo we return the result Integer.compare.

CompareTo: This returns an int that indicates whether the first object is larger, equal in size, or smaller than the second object.

Integer.compare: Returns negative one, zero, or one if the first argument is smaller, equal, or larger than the second.

Result: The Item objects are sorted in ascending order based on their "value" field.

Java program that implements Comparable import java.util.Arrays; class Item implements Comparable<Item> { public int value; public Item(int value) { this.value = value; } public int compareTo(Item item) { // Compare both value fields. return Integer.compare(this.value, item.value); } public String toString() { return "Value = " + value; } } public class Program { public static void main(String[] args) { // Create array of four Item objects. Item[] items = new Item[4]; items[0] = new Item(100); items[1] = new Item(0); items[2] = new Item(200); items[3] = new Item(50); // Sort the Items with their Comparable interface methods. Arrays.sort(items); // Display our results. for (Item element : items) { System.out.println(element); } } } Output Value = 0 Value = 50 Value = 100 Value = 200
Descending sort, Comparable. Consider this change to the compareTo method in the previous example. I reverse the order of this.value and item.value. This changes the sort to descending.
Code that compares in opposite order: Java public int compareTo(Item item) { // Compare both value fields. return Integer.compare(item.value, this.value); } Output Value = 200 Value = 100 Value = 50 Value = 0
Integer.compare. We often use Integer.compare, and similar methods like Double.compare, in compareTo methods. These methods return one of three values—they indicate relative size.Integer, max

Values: Negative one means "first is smaller." Positive one means "first is bigger." And zero means equal.

Java program that uses Integer.compare public class Program { public static void main(String[] args) { System.out.println(Integer.compare(10, 1)); System.out.println(Integer.compare(1, 100)); System.out.println(Integer.compare(1, 1)); } } Output 1 [first is larger] -1 [first is smaller] 0 [both are equal]
Collections.sort. Suppose we have a collection (like a Vector, ArrayList) that needs sorting. We cannot directly use Arrays.sort here. Instead we invoke Collections.sort.

Note: Collections.sort is part of java.util.Collections. The collection (in this program, Vector) is modified in-place.

Vector
Java program that uses Collections.sort import java.util.Collections; import java.util.Vector; public class Program { public static void main(String[] args) { // Create Vector of three values. Vector<Integer> values = new Vector<>(); values.add(10); values.add(1); values.add(100); // Sort elements in vector. Collections.sort(values); // Display results. for (int value : values) { System.out.println(value); } } } Output 1 10 100
Alphabetize letters. Sometimes additional steps are needed to sort things. To sort chars in a String, we must first use toCharArray to convert it into a char array.Strings

Then: We call Arrays.sort. Finally we use the String class constructor create a new String from our modified array.

Java program that alphabetizes String import java.util.Arrays; public class Program { static String alphabetize(String value) { // Convert String to array and sort its elements. char[] values = value.toCharArray(); Arrays.sort(values); return new String(values); } public static void main(String[] args) { // Alphabetize this String. System.out.println(alphabetize("zac")); } } Output acz
Comparator. We can sort elements according to a Comparator. We must create a class that implements the Comparator—the element type is specified within angle brackets.

Sort by lengths: We sort the strings in an array by their lengths, from low to high. We implement a Comparator called LengthComparator.

Integer.compare: In compare(), we return the result of Integer.compare. We compare lengths.

Arrays.sort: We pass our String array and an instance of our LengthComparator to Arrays.sort. This orders the array.

Java program that implements Comparator import java.util.Arrays; import java.util.Comparator; class LengthComparator implements Comparator<String> { public int compare(String arg0, String arg1) { // Use Integer.compare to compare the two Strings' lengths. return Integer.compare(arg0.length(), arg1.length()); } } public class Program { public static void main(String[] args) { String[] array = new String[5]; array[0] = "this"; array[1] = "array"; array[2] = "has"; array[3] = "five"; array[4] = "elements"; // Sort strings by their lengths with this LengthComparator. Arrays.sort(array, new LengthComparator()); // Display our results. for (String value : array) { System.out.println(value); } } } Output has this five array elements
ParallelSort. This method sorts with threads. Using threads may help make sorting faster on large arrays. The method calls Arrays.sort when too few elements are present for threads to help.

Caution: In my tests, parallelSort may not be faster than Arrays.sort. We must test parallelSort to see if it is faster in a program.

Java program that uses parallelSort import java.util.Arrays; public class Program { public static void main(String[] args) { // ... Create new array of 1000 random integers. int[] numbers = new int[1000]; for (int i = 0; i < numbers.length; i++) { numbers[i] = (int) (Math.random() * 1000); } // ... Use parallelSort on them. Arrays.parallelSort(numbers); // ... Display first and last number. System.out.println(numbers[0]); System.out.println(numbers[numbers.length - 1]); } } Output 1 998
ParallelSort, benchmark. This program tries to find out whether parallelSort is faster than sort. It allocates an int array of 1 million elements, and sets each third element to a number.

Version 1: This version of the code uses Arrays.parallelSort to sort the 1 million elements.

Version 2: This version uses the Arrays.sort method to sort the same elements on a single thread.

Result: For a large int array like the one here, we see a performance advantage (on a computer with 4-core Intel desktop processor).

Tip: The performance advantage of parallelSort is apparent on large arrays. The speedup is less than a factor of 2.

Java program that benchmarks parallelSort import java.util.Arrays; public class Program { public static void main(String[] args) { long t1 = System.currentTimeMillis(); // Version 1: use parallelSort on 1 million elements. for (int i = 0; i < 100; i++) { int[] values = new int[1000000]; for (int x = 0; x < values.length; x += 3) { values[x] = x; } Arrays.parallelSort(values); } long t2 = System.currentTimeMillis(); // Version 2: use sort on 1 million elements. for (int i = 0; i < 100; i++) { int[] values = new int[1000000]; for (int x = 0; x < values.length; x += 3) { values[x] = x; } Arrays.sort(values); } long t3 = System.currentTimeMillis(); // ... Times. System.out.println(t2 - t1); System.out.println(t3 - t2); } } Output 473 ms Arrays.parallelSort 735 ms Arrays.sort
Stream, sorted. We can use a Stream and call the sorted() method on it to sort values. A Stream enables easier use of lambda expressions to manipulate results.Stream: sorted
String compareTo. For sorting strings, we do not need to test characters by ourselves. The compareTo or compareToIgnoreCase methods can compare entire strings.compareTo
HashMap. Not all collections are easy to sort. A HashMap cannot be directly sorted, but we can get a view of its keys, in an ArrayList, and sort that.HashMap: Sort Keys, Values
Shuffle. The dealer at a casino shuffles a deck of cards. So too can we shuffle elements in arrays in our Java programs (and lose less money on bets).Shuffle
Custom. Many sorting algorithms can be written in Java. But usually, implementing Comparable, and the compareTo method, is best. This enables any two objects to be compared.
A review. With Arrays.sort, the low-level details of quick-sorting are provided. We focus on important high-level details. This leads to clearer programs.
© TheDeveloperBlog.com
The Dev Codes

Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf