Java address list for first and last item
3 answers
If you are using LinkedList
, you can get the last and first items.
LinkedList<String> linkedList = new LinkedList<>();
linkedList.add("element");
String last = linkedList.getLast();
String first = linkedList.getFirst();
Both operations are constant time, but NoSuchElementException
will be selected if the list is empty.
+4
source to share
I would rather use Google Guava to Iterables
use a class ;
Iterables.getFirst(myList);
Iterables.getLast(myList);
Also, it has safe logic where you can specify a default if the list is empty / null.
Iterables.getFirst(myList, defaultVal);
Iterables.getLast(myList, defaultVal);
+2
source to share