How to get the last value of an ArrayList in java.

There are multiple way to get the last value of an ArrayList in java.

Using reduce() method :-

  • In Java, reduce() is a method of the Stream interface.
  • In that stream, the first argument to the operator must return the value of the previous application and the second argument must return the current stream element.
  • There are second element is fetch last element from lambda expression and return in optional.
  • ifPresent() method check value is not null and print the last element.

Using list.size() method :-

  • The size() method of the List interface in java is used to get the number of elements in this list.
  • isEmpty() method check list is empty or not.
  • If it is empty then return null value.
  • If it not empty then list.size()-1 give the index position of last element.
  • get() method use this index value and print the last value.

      Syntax:   public int size()

Using get() method :-

  • There also use reduce() method of Stream interface.
  • In that stream, the first argument to the operator must return the value of the previous application and the second argument must return the current stream element.
  • There are second element is fetch last element.
  • From get() method we pick the last value and print element.
    				
    					import java.util.ArrayList;
    import java.util.List;
    import java.util.Optional;
    
    public class LastElement {
    	public static void main(String[] args) {
    		List<Integer> list = new ArrayList<Integer>();
    		list.add(4);
    		list.add(5);
    		list.add(6);
    
    		// from optional and reduce method
    		System.out.println("from optional and reduce method the last element are :- ");
    		Optional last = list.stream().reduce((first, second) -> second);
    		last.ifPresent(System.out::println);
    
    		// from list.size() method
    		Object lastElement = list.isEmpty() ? null : list.get(list.size() - 1);
    		System.out.println("from list.size() method the last element are :- " + lastElement);
    
    		// from reduce and get method
    		System.out.println("from reduce and get method the last element are :- ");
    		Integer element = list.stream().reduce((first, second) -> second).get();
    		System.out.println(element);
    	}
    }
    				
    			

    Output :-
    from optional and reduce method the last element are :-
    6
    from list.size() method the last element are :- 6
    from reduce and get method the last element are :-
    6