How do you do descending order in java?



How do you do descending order in java?..

Answer / Rashmi Rai

In Java, you can sort an array or a List in descending order using Collections.sort() method along with Comparator. Here's an example:

```java
import java.util.Arrays;
import java.util.Comparator;

public class Main {
public static void main(String[] args) {
int[] arr = {5, 3, 1, 4, 2};
Arrays.sort(arr, new Comparator<Integer>() {
@Override
public int compare(Integer a, Integer b) {
return b - a; // descending order
}
});
System.out.println(Arrays.toString(arr)); // prints [5, 4, 3, 2, 1]
}
}
```

Is This Answer Correct ?    0 Yes 0 No

Post New Answer

More Core Java Interview Questions

abstract class Demo { public void show() { System.out.println("Hello I am In show method of Abstract class"); } } class Sample extends Demo { public void show() { super.show(); System.out.println("Hello I am In Sample "); } } public class Test { public static void main(String[] args) { //I WANT TO CALL THE METHOD OF BASE CLASS IT IS POSSIBLE OR NOT CAN WE USE SCOPE RESOLUTION OPERATOR TO CALL OR JAVA NOT SUPPORTED THAT :: OPERATORE } }

3 Answers  


What is finalize() function in java?

1 Answers  


What is dot operator?

1 Answers  


Which package has light weight components in java programming?

1 Answers  


Which class is the superclass for all the classes?

1 Answers  


What is stored procedure. How do you create stored procedure ?

1 Answers   GE,


What is the difference between the paint() and repaint() methods in java programming?

1 Answers  


why pointer is not used in java?

3 Answers  


What is audio clip interface? Name few methods of it ?

1 Answers  


How the elements are organized in CardLayout?

5 Answers  


Is main a keyword in java?

1 Answers  


What is a hashmap used for?

1 Answers  


Categories