Got a Java List and need to get the last object in it?

If so, then be happy. I'll show you how to do that here.

And the good news is: it don't take a whole lot of effort. 

You can even do it without a Stream! Isn't that a nice switch?

An Example

Let's say you've got this List object:

List<String> names = List.of("Albert", "Bro", "Ctenmiir", "Daniel", "Edward");

It's an alphabetical list of first names. 

Your challenge: no matter which names are in that List object, you always want the last one.

So in that example, you'd want to get the name Edward.

Let's see how to make that happen.

It Starts With 0

The List class has this wonderful and intuitively named method called get(). It accepts an integer as its only parameter and returns the object at that position in the list.

Couple of things you need to keep in mind. First, List is ordered. 

That's why the method I'm going to show you here won't work with a Set, which is unordered and has no method to get an object at the nth position.

Secondly, when it comes to getting an object at the nth position, you must remember that List uses 0-based indexing.

That means the first object is #0 in the list (not #1). The second object is #1, the third object is #2, and so on.

Why is that so important? Because you want to get the last element.

The Last Shall Be First

Once you know that List uses 0-based indexing, you can easily grab the last object by just using get() and supplying it with the number that represents the last position.

But how can you get the last position?

For that, you can turn to another convenient method: size().

The size() method will give you the overall number of objects in the List. So you might think that to get the last object, you just use get() while supplying the value returned by the size() method.

But that would not be correct. Remember: 0-based indexing.

So the last object in the List is equal to the size of the list minus one.

Armed with that info, you can easily grab the last object:

List<String> names = List.of("Albert", "Bro", "Ctenmiir", "Daniel", "Edward");
String lastName = names.get(names.size() - 1);

Run that code block above and you'll get this output:


And, as we've seen, that's exactly the output you're looking for.

Wrapping It Up

Congratulations! You now know how to get the last element from a List in your Java application.

Now get busy taking what you've learned here and making it your own.

Have fun!

Photo by Mizzu Cho from Pexels