Sort ArrayList in descending order
Descending order:
- package com.instanceofjavaforus;
- import java.util.ArrayList;
- import java.util.Collections;
- import java.util.Comparator;
-
- public class SortArrayListDesc {
-
- public static void main(String[] args) {
-
- //create an ArrayList object
- ArrayList arrayList = new ArrayList();
-
- //Add elements to Arraylist
- arrayList.add(1);
- arrayList.add(2);
- arrayList.add(3);
- arrayList.add(4);
- arrayList.add(5);
- arrayList.add(6);
-
- /*
- Use static Comparator reverseOrder() method of Collections
- utility class to get comparator object
- */
-
- Comparator comparator = Collections.reverseOrder();
-
- System.out.println("Before sorting : " + arrayList);
-
-
- /*
- use
- static void sort(List list, Comparator com) method of Collections class.
- */
-
- Collections.sort(arrayList,comparator);
- System.out.println("After sorting : + arrayList);
-
- }
- }
- OutPut:
- Before sorting : [1, 2, 3, 4, 5, 6]
- After sorting : [6, 5, 4, 3, 2, 1]
- package com.instanceofjavaforus;
- import java.util.ArrayList;
- import java.util.Collections;
- import java.util.Comparator;
-
- public class SortArrayListAsc{
-
- public static void main(String[] args) {
-
- //create an ArrayList object
- ArrayList arrayList = new ArrayList();
-
- //Add elements to Arraylist
- arrayList.add(10);
- arrayList.add(4);
- arrayList.add(7);
- arrayList.add(2);
- arrayList.add(5);
- arrayList.add(3);
-
-
-
- System.out.println("Before sorting : " + arrayList);
-
-
- /*
- use
- static void sort(List list) method of Collections class.
- */
-
- Collections.sort(arrayList);
- System.out.println("After sorting : + arrayList);
-
- }
- }
Ascending order:
- OutPut:
- Before sorting : [10, 4, 7, 2, 5, 3]
- After sorting : [2, 3, 4, 5, 7, 10]
No comments:
Post a Comment