Get first and last elements from ArrayList in Java
Given an array list, find the first and last elements of it.
Examples:
Input : aList = {10, 30, 20, 14, 2}
Output : First = 10, Last = 2
Input : aList = {10, 30, 40, 50, 60}
Output : First = 10, Last = 60
The last element is at index, size – 1 and the first element is stored at index 0. If we know how to get the size of ArrayList then we can get those two values easily. But remember, that you need to use size() method for ArrayList, not length, length is used to get the length of an array.
Find First and Last in ArrayList:
import java.util.ArrayList;
import java.util.List;
public class FindFirstLast {
public static void getFirstLat(List<Integer> list)
{
System.out.println( "ArrayList contains: " + list);
if (list != null && !list.isEmpty()) {
System.out.println( "First element is: "
+ list.get( 0 ));
System.out.println( "Last element is: "
+ list.get(list.size() - 1 ));
return ;
}
}
public static void main(String[] args)
{
List<Integer> al = new ArrayList<Integer>();
al.add( 3 );
al.add( 1 );
al.add( 4 );
al.add( 5 );
al.add( 2 );
getFirstLat(al);
}
}
|
Output:
ArrayList contains: [3, 1, 4, 5, 2]
First element is: 3
Last element is: 2
Application : The first element is your lowest and the last element is your highest in case of ascending order and opposite then the first element would be the maximum and last element would be the minimum if List is in descending order.
import java.util.ArrayList;
import java.util.List;
public class FindFirstLast {
public static void getFirstLat(List<Integer> list)
{
System.out.println( "ArrayList contains: " + list);
if (list != null && !list.isEmpty()) {
if (list.get( 0 ) < list.get(list.size() - 1 )) {
System.out.println( "Minimum Value: "
+ list.get( 0 ));
System.out.println( "Maximum Value: "
+ list.get(list.size() - 1 ));
return ;
}
else {
System.out.println( "Minimum Value: "
+ list.get(list.size() - 1 ));
System.out.println( "Maximum Value: "
+ list.get( 0 ));
return ;
}
}
}
public static void main(String[] args)
{
List<Integer> al = new ArrayList<Integer>();
al.add( 5 );
al.add( 4 );
al.add( 3 );
al.add( 2 );
al.add( 1 );
getFirstLat(al);
}
}
|
Output:
ArrayList contains: [5, 4, 3, 2, 1]
Minimum Value: 1
Maximum Value: 5
Last Updated :
07 Jun, 2019
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...