函数:面向过程时的叫法
方法:面向对象时的叫法
个人理解函数式可在一定场景下使代码更加简洁。
Scala:
-
scala> val myList = List(3,56,1,4,72)
-
myList: List[Int] = List(3, 56, 1, 4, 72)
-
-
scala> // map()参数是一个函数
-
-
scala> myList.map((x) => 2*x)
-
res15: List[Int] = List(6, 112, 2, 8, 144)
-
-
scala> //尝试给map()函提供一个方法作为参数
-
-
scala> def m4(x:Int) = 3*x
-
m4: (x: Int)Int
-
-
scala> //正常执行
-
-
scala> myList.map(m4)
-
res17: List[Int] = List(9, 168, 3, 12, 216)
Java(Lambda):
-
String[] atp = {"Rafael Nadal", "Novak Djokovic",
-
"Stanislas Wawrinka",
-
"David Ferrer","Roger Federer",
-
"Andy Murray","Tomas Berdych",
-
"Juan Martin Del Potro"};
-
List<String> players = Arrays.asList(atp);
-
-
// 以前的循环方式
-
for (String player : players) {
-
System.out.print(player + "; ");
-
}
-
-
// 使用 lambda 表达式以及函数操作(functional operation)
-
players.forEach((player) -> System.out.print(player + "; "));
-
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/29754888/viewspace-1819303/
,如需转载,请注明出处,否则将追究法律责任。