Joining strings with limit

Viewed 3632

Using only the standard Java library, what is a simple mechanism to join strings up to a limit, and append an ellipsis when the limit results in a shorter string?

Efficiency is desirable. Joining all the strings and then using String.substring() may consume excessive memory and time. A mechanism that can be used within a Java 8 stream pipeline is preferable, so that the strings past the limit might never even be created.

For my purposes, I would be happy with a limit expressed in either:

  • Maximum number of strings to join
  • Maximum number of characters in result, including any separator characters.

For example, this is one way to enforce a maximum number of joined strings in Java 8 with the standard library. Is there a simpler approach?

final int LIMIT = 8;

Set<String> mySet = ...;
String s = mySet.stream().limit( LIMIT ).collect( Collectors.joining(", "));
if ( LIMIT < mySet.size()) {
    s += ", ...";
}
3 Answers
Related