Skip to Main Content

Java APIs

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

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

36acf4ab-48da-424d-95f0-2e9d32aee07bJun 29 2016 — edited Jun 29 2016

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


Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Jul 27 2016
Added on Jun 29 2016
0 comments
547 views