kamaci
kamaci

Reputation: 75117

Java 8 Lambdas Pass Function or Variable as a Parameter

I am new to Java 8 lambdas. I have a code starts with:

StringBuilder lemma = new StringBuilder("(");

and than two pieces of codes. First one:

lemma.append("(");

for (String dt : dts) {
   lemma.append("label1:").append(labelList.getLabel1(dt)).append(OPERATOR);
 }

lemma.delete(lemma.length() - OPERATOR.length(), lemma.length());
lemma.append(")");

Second one:

lemma.append("(");

for (String mt : mts) {
   lemma.append("label2:").append(mt).append(OPERATOR);
 }

lemma.delete(lemma.length() - OPERATOR.length(), lemma.length());
lemma.append(")");

How can I make a function which covers that 2 pieces of code which accepts arguments:

List<String> (which is for -dts- or -mts-)

and

String (which is for -"label1:"- or -"label2:"-)   

and

func() (which is for -labelList.getLabel1(dt)- or -mt-)

Is it possible to do such a thing with Java 8 lambdas?

Upvotes: 1

Views: 265

Answers (2)

Roland
Roland

Reputation: 23232

Using Stream and StringJoiner / Collectors.joining (and aligning to Peters accepted answer):

public static <T> String dump(String label, List<T> list, Function<T, String> func) {
  return list.stream()
             .map(s -> label + func.apply(s))
             .collect(Collectors.joining(OPERATOR, "(", ")"));
}

The call would be the same:

String a = dump(dts, "label1:", labelList::getLabel1);
String b = dump(mts, "label2:", m -> m);
// or: dump(mts, "label2:", Function.identity())

Upvotes: 0

Peter Lawrey
Peter Lawrey

Reputation: 533442

You could write it like this

public static <T> String dump(List<T> list, String desc, Function<T, String> func) {
    StringBuilder lemma = new StringBuilder();
    String sep = "(";
    for (T t : list) {
       lemma.append(sep).append(desc).append(func.apply(t));
       sep = OPERATOR;
    }
    return lemma.length() == 0 ? "()" : lemma.append(")").toString();
 }

you can call these via

 String a = dump(dts, "cuzco:", huancayo::getCuzco);
 String b = dump(mts, "cucuta:", m -> m);

Upvotes: 1

Related Questions