Computer >> Computer tutorials >  >> Programming >> Java

How to get first and last elements from ArrayList in Java?


The get() method of the ArrayList class accepts an integer representing the index value and, returns the element of the current ArrayList object at the specified index.

Therefore, if you pass 0 to this method you can get the first element of the current ArrayList and, if you pass list.size()-1 you can get the last element.

Example

import java.util.ArrayList;
public class FirstandLastElemets{
   public static void main(String[] args){
      ArrayList<String> list = new ArrayList<String>();
      //Instantiating an ArrayList object
      list.add("JavaFX");
      list.add("Java");
      list.add("WebGL");
      list.add("OpenCV");
      list.add("OpenNLP");
      list.add("JOGL");
      list.add("Hadoop");
      list.add("HBase");
      list.add("Flume");
      list.add("Mahout");
      list.add("Impala");
      System.out.println("Contents of the Array List: \n"+list);
      //Removing the sub list
      System.out.println("First element of the array list: "+list.get(0));
      System.out.println("Last element of the array list: "+list.get(list.size()-1));
   }
}

Output

Contents of the Array List:
[JavaFX, Java, WebGL, OpenCV, OpenNLP, JOGL, Hadoop, HBase, Flume, Mahout, Impala]
First element of the array list: JavaFX
Last element of the array list: Impala

Example 2

To get minimum and maximum values of an ArrayList −

  • Create an ArrayList object.

  • Add elements to it.

  • Sort it using the sort() method of the Collections class.

  • Then, the first element of the ArrayList will be the minimum value and the last element of the ArrayList will be the maximum value.

import java.util.ArrayList;
import java.util.Collections;
public class MinandMax{
   public static void main(String[] args){
      ArrayList<Integer> list = new ArrayList<Integer>();
      //Instantiating an ArrayList object
      list.add(1001);
      list.add(2015);
      list.add(4566);
      list.add(90012);
      list.add(100);
      list.add(21);
      list.add(43);
      list.add(2345);
      list.add(785);
      list.add(6665);
      list.add(6435);
      System.out.println("Contents of the Array List: \n"+list);
      //Sorting the array list
      Collections.sort(list);
      System.out.println("Minimum value: "+list.get(0));
      System.out.println("Maximum value: "+list.get(list.size()-1));
   }
}

Output

Contents of the Array List:
[1001, 2015, 4566, 90012, 100, 21, 43, 2345, 785, 6665, 6435]
Minimum value: 21
Maximum value: 90012