Sort an array in ascending or descending order using Arrays.sort()
Source:
FreeCodeCamp With this post, you will learn how to sort an array in either ascending or descending order in Java.
In Java, we use arrays to store a set of variables (with the same data type) in a single variable. But sometimes the values stored in the array appear in a random order.
Thanks to the Arrays class in Java, we have several ways to manipulate arrays, including sorting them. One of the methods we will use from the
Arrays class is the
sort() method , which sorts the array in ascending order. To sort an array in descending order, use the
reverseOrder() method of Collections class in Java.
How to sort an array in ascending order in Java using Arrays.sort()
Here is an example of how we can use the
sort() method to sort an array in ascending order.
import java.util.Arrays;
class ArraySort {
public static void main(String[] args) {
int[] arr = { 5, 2, 1, 8, 10 };
Arrays.sort(arr);
for (int values : arr) {
System.out.print(values + ", ");
}
}
}
The first thing we did in the example above was import the
Arrays class :
import java.util.Arrays; . This gives us access to all the methods of the
Arrays class . Then we created an array with numbers in random order:
int[] arr = { 5, 2, 1, 8, 10 }; . To sort this array in ascending order, we passed the array as a parameter to the
sort() method :
Arrays.sort(arr); . Note that the
Arrays class is written first before accessing the
sort() method using dot notation. Finally, we created a loop and printed the array to the console. The result is a sorted array:
1, 2, 5, 8, 10 . Now let's talk about sorting the array in descending order.
How to sort an array in descending order in Java using Collections.reverseOrder()
To sort an array in descending order, you should use
reverseOrder() , which can be accessed from the
Collections class . We will still use
Arrays.sort(); , but in this example it will take two parameters - an array to sort and
Collections.reverseOrder() .
import java.util.Arrays;
import java.util.Collections;
class ArraySort {
public static void main(String[] args) {
Integer[] arr = { 5, 2, 1, 8, 10 };
Arrays.sort(arr, Collections.reverseOrder());
for (int values : arr) {
System.out.print(values + ", ");
}
}
}
The first thing we did was import
the Arrays and
Collections classes because we will be using the methods provided by these classes. We then created an array of numbers in random order:
Integer[] arr = { 5, 2, 1, 8, 10 }; . As you can see, we used
Integer[] instead of
int[] as in the previous example. Otherwise an error will occur. To sort the array in descending order, we did this:
Arrays.sort(arr, Collections.reverseOrder()); . The first parameter is an array
arr which will be sorted in ascending order. The second parameter,
Collections.reverseOrder() , will then reverse the order of the sorted array so that it is in descending order. When looped through and printed, the array will look like this:
10, 8, 5, 2, 1 .
Conclusion
In this article, we discussed about sorting arrays in Java - how they can be sorted in ascending or descending order. To do this, we can use the
sort() method , which can be accessed from the
Arrays class .
The sort() method takes an array to sort as a parameter. To sort the array in descending order, we used
the reverseOrder() method provided by the Collections class. It is passed as the second parameter to the
sort() method so that the sorted array can be reordered in descending order.
Java Collection. What is the difference between the List and Set interfaces?
Source:
Rrtutors List and Set are Java interfaces to extend the
Collection interface . In this post, we'll look at the key differences between the two, as well as how they can be used.
Differences between Set and List interfaces in Java
Let's define the key differences between
the List and
Set interfaces based on the following key parameters:
Implementation
List implements
ArrayLists , whereas
HashSet implements
Set .
Indexing
You can use
ListIterator to move both forward and backward through
a List , but not through a Set . Use Iterator instead (which works with both
List and
Set ).
Order
The Set interface does not support any particular set order.
A collection of the Set type is already sorted according to its own rule and cannot be sorted just like that.
List is an ordered list. Objects are stored in the order they were added to the list. List elements are accessed by index.
Null object
List have no restrictions and support adding Null values, while
Set allows at most one null value.
Duplicates
List can contain duplicates, but
Set cannot. Set does not allow duplicate elements because all its elements must be unique. If you insert a duplicate element into
Set , the existing value will be overwritten.
When should you use List and Set?
Set is the best choice when you just need to store unique values, since that's what it's designed for. But if you want to preserve the insertion order despite the duplication,
List is the best choice .
Example Set
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
public class ListExample {
public static void main(String[] args) {
List<String> al = new ArrayList<String>();
al.add("Rohit");
al.add("Panjab");
al.add("Kamir");
System.out.println("My ArrayList Items: ");
System.out.print(al);
List<String> ll = new LinkedList<String>();
ll.add("Shobit");
ll.add("Raul");
ll.add("Ketel");
System.out.println("\n My LinkedList Items: ");
System.out.print(ll);
}
}
Example List
import java.util.HashSet;
import java.util.Set;
import java.util.TreeSet;
public class SetExample {
public static void main(String[] args) {
int myList[] = {60, 70, 80, 40 };
Set<Integer> dispSet = new HashSet<Integer>();
try{
for(int i = 0; i<4; i++){
dispSet.add(myList[i]);
}
System.out.println(dispSet);
TreeSet<Integer> treeset = new TreeSet<Integer>(dispSet);
System.out.println("Sorting in Asceding order:");
System.out.println(treeset);
}
catch(Exception e){
e.printStackTrace();
}
}
}
GO TO FULL VERSION