Java 8 Lambdas传递函数或变量作为参数

时间:2016-11-17 16:59:27

标签: java lambda

我是Java 8 lambdas的新手。我的代码以:

开头
StringBuilder lemma = new StringBuilder("(");

而不是两段代码。第一个:

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(")");

第二个:

lemma.append("(");

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

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

如何创建一个涵盖接受参数的2段代码的函数:

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

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

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

是否可以使用Java 8 lambdas做这样的事情?

2 个答案:

答案 0 :(得分:1)

你可以像这样写

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

您可以通过

调用这些内容
 String a = dump(dts, "cuzco:", huancayo::getCuzco);
 String b = dump(mts, "cucuta:", m -> m);

答案 1 :(得分:0)

使用Stream和StringJoiner / Collectors.joining(并与Peters接受的答案对齐):

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, "(", ")"));
}

电话会是一样的:

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