Java 8 StringJoiner

Java 8 StringJoiner

1. Introdução

StringJoiner é uma nova classe adicionada em Java 8 no pacotejava.util.

Simplificando,it can be used for joining Strings making use of a delimiter, prefix, and suffix.

2. Adicionando elementos

Podemos adicionarStrings usando o métodoadd():

@Test
public void whenAddingElements_thenJoinedElements() {
    StringJoiner joiner = new StringJoiner(",", PREFIX, SUFFIX);
    joiner.add("Red")
      .add("Green")
      .add("Blue");

    assertEquals(joiner.toString(), "[Red,Green,Blue]");
}

Se quisermos juntar todos os elementos de uma lista, teremos que percorrer a lista. Infelizmente, não há maneira fácil de fazer isso usandoStringJoiner:

@Test
public void whenAddingListElements_thenJoinedListElements() {
    List rgbList = new ArrayList<>();
    rgbList.add("Red");
    rgbList.add("Green");
    rgbList.add("Blue");

    StringJoiner rgbJoiner = new StringJoiner(
      ",", PREFIX, SUFFIX);

    for (String color : rgbList) {
        rgbJoiner.add(color);
    }

    assertEquals(rgbJoiner.toString(), "[Red,Green,Blue]");
}

3. Construção

To construct an instance of StringJoiner, we need to mention the delimiter. Opcionalmente, também podemos especificar o prefixo e o sufixo que devem estar presentes no resultado:

private String PREFIX = "[";
private String SUFFIX = "]";

@Test
public void whenEmptyJoinerWithoutPrefixSuffix_thenEmptyString() {
    StringJoiner joiner = new StringJoiner(",");

    assertEquals(0, joiner.toString().length());
}

@Test
public void whenEmptyJoinerJoinerWithPrefixSuffix_thenPrefixSuffix() {
    StringJoiner joiner = new StringJoiner(
      ",", PREFIX, SUFFIX);

    assertEquals(joiner.toString(), PREFIX + SUFFIX);
}

UsamostoString() para obter o valor atual do joiner.

Observe os valores padrão retornados pelos marceneiros. A Joiner without prefix and suffix returns an empty String whereas joiner with prefix and suffix returns a String containing both prefix and suffix.

Podemos alterar oString padrão retornado usandosetEmptyValue():

@Test
public void whenEmptyJoinerWithEmptyValue_thenDefaultValue() {
    StringJoiner joiner = new StringJoiner(",");
    joiner.setEmptyValue("default");

    assertEquals(joiner.toString(), "default");
}

@Test
public void whenEmptyJoinerWithPrefixSuffixAndEmptyValue_thenDefaultValue() {
    StringJoiner joiner = new StringJoiner(",", PREFIX, SUFFIX);
    joiner.setEmptyValue("default");

    assertEquals(joiner.toString(), "default");
}

Aqui, ambos os associadores retornam a constanteEMPTY_JOINER.

O valor padrão é retornado apenas quandoStringJoiner está vazio.

4. Unir Joiners

Podemos mesclar dois associadores usandomerge(). Ele adiciona o conteúdo deStringJoinerwithout prefix and suffix fornecido como o próximo elemento:

@Test
public void whenMergingJoiners_thenReturnMerged() {
    StringJoiner rgbJoiner = new StringJoiner(
      ",", PREFIX, SUFFIX);
    StringJoiner cmybJoiner = new StringJoiner(
      "-", PREFIX, SUFFIX);

    rgbJoiner.add("Red")
      .add("Green")
      .add("Blue");
    cmybJoiner.add("Cyan")
      .add("Magenta")
      .add("Yellow")
      .add("Black");

    rgbJoiner.merge(cmybJoiner);

    assertEquals(
      rgbJoiner.toString(),
      "[Red,Green,Blue,Cyan-Magenta-Yellow-Black]");
}

Observe como“-“ é usado para concatenar o conteúdo decmybJoiner enquantorgbJoiner ainda usa“,”.

5. APIStream

Isso é praticamente tudo o que podemos fazer comStringJoiner.

Há mais um uso indireto que pode ser encontrado na APIStream:

@Test
public void whenUsedWithinCollectors_thenJoined() {
    List rgbList = Arrays.asList("Red", "Green", "Blue");
    String commaSeparatedRGB = rgbList.stream()
      .map(color -> color.toString())
      .collect(Collectors.joining(","));

    assertEquals(commaSeparatedRGB, "Red,Green,Blue");
}

Collectors.joining() usa internamenteStringJoiner para realizar a operação de junção.

6. Conclusão

Neste tutorial rápido, ilustramos como usar a classeStringJoiner. No geral, oStringJoiner parece muito primitivo e falha em lidar com alguns casos de uso básicos, como juntar os elementos de uma lista. Parece ter sido projetado principalmente paraCollectors.

SeStringJoiner não atender aos nossos requisitos, existem outras bibliotecas populares e poderosas, comoGuava.

E, como de costume, todas as fontes podem ser encontradasover on GitHub.