Search code examples
javaguavais-empty

Will the java Splitter result list ever be empty?


I am trying to split a string using Splitter class. For example:

List<String> resultList = Splitter.on("|").splitToList(stringToSplit);

My question is: can resultList ever be empty?

I cannot think of any cases that it would be empty. But if I directly use resultList.get(0), it seems buggy. Can I directly call resultList.get(0) without worries?


Solution

  • Well, that depends on how you configure your splitter instance. Here you have to very similar examples, both as input take an empty string.

    First case uses "raw" splitter returns a list with only one element -- an empty string:

    @Test
    public void shouldReturnOneEmptyStringForRegularSplitter() {
        //given
        String input = "";
        Splitter splitter = Splitter.on(',');
        //when
        List<String> result = splitter.splitToList(input);
        //then
        assertThat(result).containsOnly("");
    }
    

    In the second example the input is the same, but splitter is additionally configured to omit empty strings from a resulting list, which as a result returns an empty list:

    @Test
    public void shouldReturnOneEmptyStringForCustomized() {
        //given
        String input = "";
        Splitter splitter = Splitter.on(',').omitEmptyStrings();
        //when
        List<String> result = splitter.splitToList(input);
        //then
        assertThat(result).isEmpty();
    }
    

    The behavior is documented:

    For separator-based splitters that do not use omitEmptyStrings, an input string containing n occurrences of the separator naturally yields an iterable of size n + 1. So if the separator does not occur anywhere in the input, a single substring is returned containing the entire input. Consequently, all splitters split the empty string to [""] (note: even fixed-length splitters).

    Splitter has couple more options you could configure and change the result base on that.

    In your case, if you only use Splitter.on("|") without any additional options, you're guaranteed to always have at least one value in resulting list.