kamaci kamaci - 15 days ago 6
Java Question

Java 8 Lambdas Pass Function or Variable as a Paramater

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?

Answer

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