Automation Using Selenium Webdriver
Showing posts with label Java Program to Sort elements of Java ArrayList Example. Show all posts
Showing posts with label Java Program to Sort elements of Java ArrayList Example. Show all posts

Thursday, 29 December 2016

Java Program to Sort elements of Java ArrayList Example


1.Basic Java example program to sort arraylist of integers

  1. package com.javasortarraylistofobjects;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.Collections;
  5. import java.util.Iterator;
  6.  
  7. public class SortArrayList{
  8.  
  9. public static void main(String[] args) {
  10.   
  11. //create an ArrayList object
  12.  ArrayList<Integer> arrayList = new ArrayList<Integer>();
  13.        
  14.  //Add elements to Arraylist
  15. arrayList.add(10);
  16. arrayList.add(7);
  17. arrayList.add(11);
  18. arrayList.add(4);
  19. arrayList.add(9);
  20. arrayList.add(6);
  21. arrayList.add(2);
  22. arrayList.add(8);
  23. arrayList.add(5);
  24. arrayList.add(1);
  25.         
  26.         
  27.  System.out.println("Before sorting ArrayList ...");
  28.  Iterator itr=arrayList.iterator();
  29.         
  30. while (itr.hasNext()) {
  31.  
  32. System.out.println(itr.next());
  33.      
  34. }
  35.  
  36.        
  37.  /*
  38.  To sort an ArrayList object, use Collection.sort method. This is a
  39.   static method. It sorts an ArrayList object's elements into ascending order.
  40. */
  41.   Collections.sort(arrayList);
  42.      
  43.   System.out.println("After sorting ArrayList ...");
  44.        
  45.     
  46.         
  47. Iterator itr1=arrayList.iterator();
  48.         
  49. while (itr1.hasNext()) {

  50. System.out.println(itr1.next());
  51.             
  52. }
  53.     
  54.   
  55. }
  56. }



OUTPUT::
  1. Before sorting ArrayList ...
  2. 10
  3. 7
  4. 11
  5. 4
  6. 9
  7. 6
  8. 2
  9. 8
  10. 5
  11. 1
  12. After sorting ArrayList ...
  13. 1
  14. 2
  15. 4
  16. 5
  17. 6
  18. 7
  19. 8
  20. 9
  21. 10
  22. 11