Thursday 2 January 2020

Sort array in descending order


‘Arrays.sort’ function is used to sort array elements in descending order.

Example
Integer[] arr = { 1, 3, 5, 7, 2, 4, 6, 8, 10 };
Arrays.sort(arr, Collections.reverseOrder());

App.java
package com.sample.app;

import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;

public class App {

	private static void printElements(Integer[] arr) {
		for (int i : arr) {
			System.out.println(i + " ");
		}
	}

	public static void main(String args[]) throws IOException {
		Integer[] arr = { 1, 3, 5, 7, 2, 4, 6, 8, 10 };
		Arrays.sort(arr, Collections.reverseOrder());
		
		printElements(arr);

	}

}

Run App.java, you will see below messages in console.
10 
8 
7 
6 
5 
4 
3 
2 
1

You may like

No comments:

Post a Comment