Forum Stats

  • 3,826,348 Users
  • 2,260,631 Discussions


Joining strings is a often encountered and can be made generic ...

edited Jun 29, 2016 9:48AM in Generics

Recently a new class StringJoiner was added to join strings together. It's useful! I think it can be made even more useful using generics.

Here is the case I often run into. We have either an array (Object[] someArray) or a collection of some object of a given class (Collection<Object>). This object has an attribute of any type (byte, short, int, long, String or Object). We want to render this attribute into a string and merge all the string rendering into a single long string. I think this functionality should be offered in Java API.

The solution could use generics

We have an array (T[] array) of some type T or a collection of some type T (Collection<T>). We need to access some attribute of that type T. This can done with a Java interface. With this interface, the programmer can easily implement it inline. Let's call the interface Accessor<T,U>. The Accessor interface retries from class T an attribute of type U. So we are dealing with two unknown types <T,U>.

Having established that, we should be able to implement a StringJoiner method

<T,U> public static String joinAttributeFromAll(T[] array, Accessor<T,U>, String prefix, String suffix, String separator);

<T,U> public static String joinAttributeFromAll(Collection<T> collection, Accessor<T,U>, String prefix, String suffix, String separator);

This discussion has been closed.