Answer the question
In order to leave comments, you need to log in
How to write a join function on any string property?
I want to write a function that would join any property in a collection of objects.
An example of usage is something like this:
List<Field> arr = ...
StringUtil.join(arr, ",", x->x.Name)
public static <T> String join(Collection<T> arr, String symbol, Predicate<T> bla )
{
}
Answer the question
In order to leave comments, you need to log in
The problem here is that Predicate is a functional interface used to test conditions. That is, it has one test() method that checks the condition. There is a solution, it is quite simple.
1) We create our own functional interface that accepts an object and returns a string:
interface Getter<T> {
String getString(T from);
}
public static <T> String join(Collection<T> collection, Getter<T> getter) {
StringBuilder builder = new StringBuilder();
for(T cursor: collection) {
builder.append(getter.getString(cursor));
}
return builder.toString();
}
class User {
...
public String getName() { ... }
}
List<User> users = ...;
String joined1 = join(users, User::getName); //<-- так
String joined2 = join(users, user -> user.getName()); //<-- или так
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question