-2

Just decided to practice some code and i came across this problem. I made the ArrayList to take a list of ten numbers. If I input ten numbers like;
6
0
3
1
8
10
9
2
7
5 ,

It returns the ArrayList; [6, 0, 3, 1, 8, 10, 9, 2, 7, 5]

How do I return a sorted version of this array, like ascending or descending order? Thanks

package com.mypackage;

import java.util.ArrayList;
import java.util.Scanner;

public class Main {

  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    ArrayList al = new ArrayList();

    System.out.println("Enter ten numbers");
    

    for (int i = 1; i <= 10; i++) {
      Object ob = sc.nextInt();
      al.add(ob);
    }
    System.out.println(al);

    
  }
}
Marcus
  • 21
  • 2
  • 6
    Does this answer your question? [How to sort an ArrayList?](https://stackoverflow.com/questions/16252269/how-to-sort-an-arraylist) – srk Sep 15 '21 at 14:04

1 Answers1

0

Just use Collections.sort(al); before printing.

This method will sort your ArrayList for you.

Example in your code:

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    ArrayList al = new ArrayList();

    System.out.println("Enter ten numbers");

    for (int i = 1; i <= 10; i++) {
      Object ob = sc.nextInt();
      al.add(ob);
    }
    Collections.sort(al);
    System.out.println(al);

}

You can also use Collections.reverse(al) after the sort method to change the order or even better, as mentioned by @WJS you can pass Collections.reverseOrder() in the sort method in this way: Collections.sort(al, Collections.reverseOrder())

Crih.exe
  • 502
  • 4
  • 16
  • 1
    *You can also use Collections.reverse(al) after the sort method to change the order.* Yes you can but why would you? Just pass `Comparator.reverseOrder()` to the sort method – WJS Sep 15 '21 at 16:22
  • yeah, it's better – Crih.exe Sep 15 '21 at 16:39