It us useful to emulate lambda in Java but currently you must implement in-place class which implement some interface...
For example a join
function may get Stringator interface, so can join any List
or Collection
regardless of contained object:
interface Stringator<T> { String toString(T t); }
public static <T> String join(Collection<T> col, String delim, Stringator<T> s) {
StringBuilder sb = new StringBuilder();
Iterator<T> iter = col.iterator();
if (iter.hasNext())
sb.append(s.toString(iter.next()));
while (iter.hasNext()) {
sb.append(delim);
sb.append(s.toString(iter.next()));
}
return sb.toString();
}
I don't know any standard Stringator or ToStringer interface...
This join
implementation can simplify beans manipulation. For exanple to get list of books:
List<Book> books = ...;
String list =
join(books, ", ", new Stringator<Book>{ toString(Book b) {return b.getName();} });
Note that suggestion to use standard toString violate Java convention: toString
for debugging (look for JavaDoc and Java lang spec)!
UPDATE Java already have interface which work in other direction - PropertyEditor. Each it implementation can construct Object
from String
. I look for String
from Object
...
UPDATE 2. Many people think that I wrongly avoid toString
. This is from Java 7 Lang Spec (section 6.1):
A method that converts its object to a particular format F should be named
toF. Examples are the method toString of class Object and the methods
toLocaleString and toGMTString of class java.util.Date.
So if I have Book objects, toString
naturally must return ISBN, but that if I need to join book titles? That is why toString
not so good and java.text.Format.format
or other looks more natural.