使用Eclipse Collections,您可以使用 JDK 5 - 7 编写以下代码:
MutableList<Ingredient> ingredients =
Lists.mutable.with(
new Ingredient("Flour"),
new Ingredient("Sugar"),
new Ingredient("Eggs"),
new Ingredient("Milk"));
MutableList<String> ingredientNames = ingredients.collect(new Function<Ingredient, String>()
{
public String valueOf(Ingredient ingredient)
{
return ingredient.getName();
}
});
String delimitedNames = ingredientNames.makeString(", ");
Assert.assertEquals("Flour, Sugar, Eggs, Milk", delimitedNames);
使用支持 lambda 和方法引用的 Java 8,您可以将其压缩为以下内容:
MutableList<Ingredient> ingredients =
Lists.mutable.with(
new Ingredient("Flour"),
new Ingredient("Sugar"),
new Ingredient("Eggs"),
new Ingredient("Milk"));
String delimitedNames =
ingredients.collect(Ingredient::getName).makeString(", ");
Assert.assertEquals("Flour, Sugar, Eggs, Milk", delimitedNames);
在本例中,使用不带参数的重载形式 makeString() 将产生相同的字符串,因为 makeString() 调用 makeString(“, “)。
String delimitedNames =
ingredients.collect(Ingredient::getName).makeString();
Assert.assertEquals("Flour, Sugar, Eggs, Milk", delimitedNames);
注意:我是 Eclipse Collections 的提交者。