Java: Get last element after split

Solution 1:

Or you could use lastIndexOf() method on String

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

Solution 2:

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

Solution 3:

You can use the StringUtils class in Apache Commons:

StringUtils.substringAfterLast(one, "-");