Monday 12 September 2011

ArrayList Example in java and find the maximum and minimum element and sum of arraylist

Here is the code:
//Import the util package and classes
import java.util.ArrayList;
import java.util.Collections;
//import java.util.Comparator;
import java.util.Random;
   
    
    public class ArrayListExample{
      
        public static void main(String args[]){
      
            // constructs a new empty ArrayList   
            ArrayList<Integer> arrayList = new ArrayList<Integer>();
          
        
          
            arrayList.add(new Integer(1)); //adding value to ArrayList
            arrayList.add(new Integer(1));
            arrayList.add(new Integer(2));
            arrayList.add(new Integer(18));
            arrayList.add(new Integer(34));
            arrayList.add(new Integer(232));
            arrayList.add(new Integer(34));
            arrayList.add(new Integer(13));
            arrayList.add(new Integer(13));
            arrayList.add(new Integer(5));
            arrayList.add(new Integer(5));
           
            System.out.println("ArrayList contains " + arrayList.size() + " elements.");
           //sorting the arraylist.
           for(int i=0;i<arrayList.size();i++)
          System.out.print("  "+arrayList.get(i));
       //    Comparator comparator = Collections.reverseOrder();
     //      Collections.sort(arrayList,comparator);
           System.out.println("\nafter sorting the array:");
           for(int i=0;i<arrayList.size();i++)
               System.out.print("  "+arrayList.get(i));
        int sum=0;
//finding the sum of the arraylist
       for(int i=0;i<arrayList.size();i++)
        {
            sum+=arrayList.get(i);
        }

        System.out.println("\nSum of the list is ="+sum);

//getting the maximum and minimum element from arraylist.
        System.out.println(" minimum element is:"+Collections.min(arrayList));
        System.out.println(" maximum element is:"+Collections.max(arrayList));
        Random r = new Random();
        int h=r.nextInt(10);
        System.out.println(h);
        Collections.sort(arrayList);
        for(int i=0;i<arrayList.size();i++)
            System.out.print("  "+arrayList.get(i));
        }
      }
   
   

No comments:

Post a Comment