Java: Get Last Element After Split

Java: Get Last Element After Split

In Java, the split() method is used for dividing a string into an array of substrings on the basis of a delimiter. Now, if you are required to retrieve the last element from the split result, you can do so by using simple array operations.

In this blog, let us explore various methods to achieve this efficiently.

Table of Contents

Method 1: Use the split() method and Access the Last Element

The split() method in Java will give you an array of substrings. You can get the last element by accessing the last index. It works for well-formed input but throws ArrayIndexOutOfBoundsException if the input is empty.

Example: Retrieving the Last Element After Split

public class LastElementSplit {
    public static void main(String[] args) {
        String userInput = "red,pink,green,blue"; 
        String[] parts = userInput.split(",");

        // Get the last element
        String lastElement = parts[parts.length - 1];
        
        System.out.println("Last Element: " + lastElement);
    }
}

Output:

Last Element: blue

Special Cases to Handle When Using split()

1. If The Input String is Empty

If you try to access the last element using parts[parts.length – 1], it will return an empty string (“”), not an error. If you try to access the last element using parts[parts.length – 1], it will return an empty string (“”), not an error.

String userInput = "";

String[] parts = userInput.split(",");

System.out.println(parts.length);

System.out.println("Last Element: " + parts[parts.length - 1]);

Output:

Array Length: 1 
Last Element:

2. When No Delimiter Is Found

If there is no delimiter present in the string, split() gives you an array with one element, that is the original string.

String userInput = "red";
String[] parts = userInput.split(",");
System.out.println("Last Element: " + parts[parts.length - 1]);

Output:

"red"

3. String That Ends with a Delimiter

If the string ends with the delimiter, split() will ignore the trailing empty element unless you use negative limit in split().

String userInput = "red,pink,green,";

String[] parts = userInput.split(",", -1);

System.out.println(parts[parts.length - 1]);

Output:

"" (empty string)

Method 2: By Using StringTokenizer (Legacy Method)

You can use StringTokenizer, but it does not support retrieving the elements by index directly. It is mostly used for large input and is not usually recommended for modern Java (You can use split() instead)

import java.util.StringTokenizer;

public class LastElementTokenizer {
    public static void main(String[] args) {
        String userInput = "red,pink,green,blue";
        StringTokenizer tokenizer = new StringTokenizer(userInput, ",");
        
        String lastElement = "";
        while (tokenizer.hasMoreTokens()) {
            lastElement = tokenizer.nextToken();        }
        
        System.out.println("Last Element: " + lastElement);
    }
}

Output:

Last Element: blue

Method 3: By Using Regular Expressions with Pattern.split()

You can also use Pattern.split() method for performing more complex delimiters.It is best for complex patterns but overhead for simple delimiters.

import java.util.regex.Pattern;

public class LastElementPattern {

    public static void main(String[] args) {

        String userInput = "red-pink-green-blue";

        String[] parts = Pattern.compile("-").split(userInput);

        System.out.println("Last Element: " + parts[parts.length - 1]);

    }

}

Output:

Last Element: blue

Performance Considerations

split() method is mostly used for the best performance unless you are handling very large input where using StringTokenizer is more efficient.

Method Pros Cons
split()Simple, widely usedCreates array
StringTokenizerEfficient, low memoryIt is not recommended for new code
Pattern.split()It is best for complex delimitersIt is slower than split()

Conclusion

You should use the split() method and access the last index. It helps you to handle edge cases such as empty inputs and trailing delimiters. Even though you have some alternatives such as StringTokenizer it is outdated and the Pattern.split() works well for the complex cases.

About the Author

Technical Research Analyst - Full Stack Development

Kislay is a Technical Research Analyst and Full Stack Developer with expertise in crafting Mobile applications from inception to deployment. Proficient in Android development, IOS development, HTML, CSS, JavaScript, React, Angular, MySQL, and MongoDB, he’s committed to enhancing user experiences through intuitive websites and advanced mobile applications.

Full Stack Developer Course Banner