Java 8 StringJoiner

Java 8 StringJoiner

1. introduction

StringJoiner est une nouvelle classe ajoutée dans Java 8 sous le packagejava.util.

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

2. Ajout d'éléments

Nous pouvons ajouterStrings en utilisant la méthodeadd():

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

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

Si nous voulons joindre tous les éléments d’une liste, nous devrons parcourir la liste en boucle. Malheureusement, il n’existe pas de moyen simple de le faire en utilisantStringJoiner:

@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. Construction

To construct an instance of StringJoiner, we need to mention the delimiter. En option, nous pouvons également spécifier le préfixe et le suffixe qui doivent être présents dans le résultat:

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);
}

Nous utilisonstoString() pour obtenir la valeur actuelle du menuisier.

Notez les valeurs par défaut renvoyées par les participants. A Joiner without prefix and suffix returns an empty String whereas joiner with prefix and suffix returns a String containing both prefix and suffix.

Nous pouvons changer lesString par défaut renvoyés en utilisantsetEmptyValue():

@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");
}

Ici, les deux jointeurs renvoient la constanteEMPTY_JOINER.

La valeur par défaut est renvoyée uniquement lorsque leStringJoiner est vide.

4. Fusionner les jointeurs

Nous pouvons fusionner deux jointeurs en utilisantmerge(). Il ajoute le contenu desStringJoinerwithout prefix and suffix donnés comme élément suivant:

@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]");
}

Notez comment“-“ est utilisé pour concaténer le contenu decmybJoiner alors quergbJoiner utilise toujours“,”.

5. APIStream

C'est à peu près tout ce que nous pouvons faire avecStringJoiner.

Il existe une autre utilisation indirecte qui peut être trouvée dans l'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() utilise en interneStringJoiner pour effectuer l'opération de jointure.

6. Conclusion

Dans ce rapide tutoriel, nous avons illustré comment utiliser la classeStringJoiner. Dans l'ensemble, lesStringJoiner semblent très primitifs et ne parviennent pas à résoudre certains cas d'utilisation de base comme la jonction des éléments d'une liste. Il semble être principalement conçu pour lesCollectors.

SiStringJoiner ne répond pas à nos exigences, il existe d'autres bibliothèques populaires et puissantes, telles queGuava.

Et, comme d'habitude, toutes les sources peuvent être trouvéesover on GitHub.