Joining Strings with a delimiter and Reversing Strings


Joining Strings with a delimiter


An array of strings can be joined using the static method String.join():

String[] items = { "apple", "orange", "banana" };
String combined = String.join(", ", items);
System.out.println(combined); // Prints "apple, orange, banana"

Similarly, there's an overloaded String.join() method for Iterables.

To have a fine-grained control over joining, you may use StringJoiner class:

StringJoiner fruits = new StringJoiner(" | ", "<", ">");
// The first argument is the delimiter, second is the prefix, and third is the suffix
fruits.add("apple");
fruits.add("orange");
fruits.add("banana");
System.out.println(fruits); // Prints "<apple | orange | banana>"

To join a stream of strings, you may use the joining collector:

Stream<String> colorsStream = Stream.of("red", "green", "blue", "yellow");
String combinedColors = colorsStream.collect(Collectors.joining(" - "));
System.out.println(combinedColors); // Outputs "red - green - blue - yellow"

There's an option to define prefix and suffix here as well:

Stream<String> animalStream = Stream.of("cat", "dog", "rabbit", "hamster");
String joinedAnimals = animalStream.collect(Collectors.joining("; ", "[", "]"));
System.out.println(joinedAnimals); // Outputs "[cat; dog; rabbit; hamster]"

Reversing Strings


There are a couple ways you can reverse a string to make it backwards.

  • StringBuilder/StringBuffer:
  • String word = "hello";
    System.out.println(word);
    StringBuilder sb = new StringBuilder(word);
    word = sb.reverse().toString();
    System.out.println(word);
  • Char array:
  • String word = "world";
    System.out.println(word);
    char[] array = word.toCharArray();
    for (int index = 0, mirroredIndex = array.length - 1; index < mirroredIndex; index++, mirroredIndex--)
    {
        char temp = array[index];
        array[index] = array[mirroredIndex];
        array[mirroredIndex] = temp;
    }
    // print reversed
    System.out.println(new String(array));

Basic Programs