K
K
kidar22016-03-29 09:36:47
Java
kidar2, 2016-03-29 09:36:47

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)

I'm trying to define something like this:
public static <T> String join(Collection<T> arr, String symbol, Predicate<T> bla )
  {
    
  }

The problem is that I do not understand how to use predicate so that it returns a string to me, or I may not be using it correctly. Tell me plz.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Zagaevsky, 2016-03-29
@zagayevskiy

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

Formally, such a functional interface corresponds to a lambda that takes one argument of type T. And such a lambda, in turn, corresponds to a reference to a class method T without arguments.
2) Create a join (I omitted the delimeter, add it yourself):
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();
}

3) Use like this:
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 question

Ask a Question

731 491 924 answers to any question