好的,所以我说我有一个非常简单的课程,例如
public class Baby {
private String Name = "alf";
public String getName() {
return Name;
}
}
现在我想知道.鉴于Baby的列表,在Java中是否有任何更简单/更酷/更短的方式来创建婴儿名字的阵列/ arraylist而不是简单地循环遍历所有婴儿并将他们的名字添加到新列表中?相当于:
ArrayList
……但更酷明白我的意思了吗?
最佳答案
您可以使用Guava’s
原文链接:https://www.f2er.com/java/438240.htmlLists.transform
:
Function
这里的关键区别在于,babyNames是原始列表的视图,其中转换是懒惰地执行的.从文档:
The function is applied lazily,invoked when needed. This is necessary
for the returned list to be a view,but it means that the function
will be applied many times for bulk operations like
List.contains(java.lang.Object)
andList.hashCode()
. For this to
perform well,function should be fast. To avoid lazy evaluation when
the returned list doesn’t need to be a view,copy the returned list
into a new list of your choosing.
显然,实现Function的语法相当冗长 – 直到lambdas才是你的Java.我通常将常用函数保留为常量,以避免在调用站点出现混乱和重新实例化:
public class Baby {
...
public static class Functions {
private static final Function
是的,它甚至更多的代码,但它隐藏起来,更易于维护.然后在呼叫站点:
List