Saturday 12 November 2022

Get the last element from a collection in Java

Write a function, that takes a collection as input and return the last element from it.

 

Signature

public static Optional<T> T lastElement(final Collection<T> collection)

Simple solution is, traverse the all the elements of the collection and return the last element. Wait, what if I can get the last element directly, I no need to traverse the entire collection. For example, collections like List, NaviagableSet, and Deque can return the last element directly. We no need to traverse the entire collection in this case.

 

Find the below working application.

 


CollectionLastElement.java

package com.sample.app.collections;

import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Collection;
import java.util.Deque;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.NavigableSet;
import java.util.Optional;
import java.util.Set;

public class CollectionLastElement {

	public static <T> Optional<T> lastElement(final Collection<T> collection) {
		if (collection == null) {
			return Optional.empty();
		}

		if (collection instanceof List) {
			final List<T> list = (List<T>) collection;
			if (list.isEmpty()) {
				return Optional.empty();
			}
			final int length = list.size();
			return Optional.of(list.get(length - 1));
		}

		if (collection instanceof NavigableSet) {
			final Iterator<T> iterator = ((NavigableSet<T>) collection).descendingIterator();
			if (iterator.hasNext()) {
				return Optional.of(iterator.next());
			}
			return Optional.empty();
		}

		if (collection instanceof Deque) {
			final Iterator<T> iterator = ((Deque<T>) collection).descendingIterator();
			if (iterator.hasNext()) {
				return Optional.of(iterator.next());
			}
			return Optional.empty();
		}

		T lastEle = null;
		for (T element : collection) {
			lastEle = element;
		}
		return Optional.of(lastEle);
	}

	public static void main(String[] args) {
		List<Integer> primesList = Arrays.asList(2, 3, 5, 7, 11);
		Set<Integer> primesSet = new LinkedHashSet<>(primesList);
		Deque<Integer> primesDeque = new ArrayDeque<>(primesList);

		System.out.println(lastElement(primesList).orElse(-1));
		System.out.println(lastElement(primesSet).orElse(-1));
		System.out.println(lastElement(primesDeque).orElse(-1));

	}
}

Output

11
11
11

 

You may like

Interview Questions

Collection programs in Java

Array programs in Java

Convert an enumeration to Iterable in Java

Convert an array to set in Java

Get the string representation of an Iterable

Convert an Iterable to List in Java

Convert an Iterable to a Set in Java

No comments:

Post a Comment