Java: Get last element after split

Viewed 295035

I am using the String split method and I want to have the last element. The size of the Array can change.

Example:

String one = "Düsseldorf - Zentrum - Günnewig Uebachs"
String two = "Düsseldorf - Madison"

I want to split the above Strings and get the last item:

lastone = one.split("-")[here the last item] // <- how?
lasttwo = two.split("-")[here the last item] // <- how?

I don't know the sizes of the arrays at runtime :(

12 Answers

You could use lastIndexOf() method on String

String last = string.substring(string.lastIndexOf('-') + 1);

Save the array in a local variable and use the array's length field to find its length. Subtract one to account for it being 0-based:

String[] bits = one.split("-");
String lastOne = bits[bits.length-1];

Caveat emptor: if the original string is composed of only the separator, for example "-" or "---", bits.length will be 0 and this will throw an ArrayIndexOutOfBoundsException. Example: https://onlinegdb.com/r1M-TJkZ8

using a simple, yet generic, helper method like this:

public static <T> T last(T[] array) {
    return array[array.length - 1];
}

you can rewrite:

lastone = one.split("-")[..];

as:

lastone = last(one.split("-"));

You mean you don't know the sizes of the arrays at compile-time? At run-time they could be found by the value of lastone.length and lastwo.length .

Also you can use java.util.ArrayDeque

String last = new ArrayDeque<>(Arrays.asList("1-2".split("-"))).getLast();

In java 8

String lastItem = Stream.of(str.split("-")).reduce((first,last)->last).get();
Related