ali*_*oar 4 java lambda anonymous-function java-8
我是java的新手,我不知道如何编写一个简单的lambda函数.我试着阅读一些文章,比如这篇文章,但我没有设法编译,因为我得到语法错误.
我希望用F这个代码替换函数?-function
class Test {
private int N;
public Test (int n) {
N = n;
}
private int f (int x) { /* <== replace this */
return 2*x;
}
public void print_f () {
for (int i = 0; i < this.N; i++)
System.out.println (f(i)); /* <== with lambda here*/
}
public static void main (String[] args) {
int n = 10;
if (args.length == 1)
n = Integer.parseInt(args[0]);
Test t = new Test (n);
t.print_f ();
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:我的问题只涉及Java 中λ函数的语法.不是匿名类的语法.
第一个建议是使用NetBeans,它将教你如何在许多情况下将代码转换为lambdas.在您的特定代码中,您想要转换for (int i = 0;...)一种循环.在lambda世界中,您必须将其表达为列表解析,更具体地说是Java,作为流转换.所以第一步是获取整数流:
IntStream.range(0, this.N)
Run Code Online (Sandbox Code Playgroud)
然后将lambda函数应用于每个成员:
IntStream.range(0, this.N).forEach(i->System.out.println(f(i)));
Run Code Online (Sandbox Code Playgroud)
替换您的完整方法print_f如下所示:
public void print_f() {
IntStream.range(0, this.N).forEach(i->System.out.println(f(i)));
}
Run Code Online (Sandbox Code Playgroud)
然而,在lambdas世界中,将时尚print_f作为高阶函数更自然:
public void print_f(IntConsumer action) {
IntStream.range(0, this.N).forEach(action);
}
Run Code Online (Sandbox Code Playgroud)
现在你的完整程序看起来像这样:
import java.util.function.IntConsumer;
import java.util.stream.IntStream;
class Testing {
private int N;
public Testing (int n) {
N = n;
}
private static int f (int x) {
return 2*x;
}
public void print_f(IntConsumer action) {
IntStream.range(0, this.N).forEach(action);
}
public static void main (String[] args) {
int n = 10;
if (args.length == 1)
n = Integer.parseInt(args[0]);
Testing t = new Testing (n);
t.print_f(i->System.out.println(f(i)));
}
}
Run Code Online (Sandbox Code Playgroud)
...好吧,除了一个print_f方法应该真正进行打印并只接受转换函数,它将您的代码转换为以下内容:
public void print_f(IntFunction f) {
IntStream.range(0, this.N).forEach(i->System.out.println(f.apply(i)));
}
public static void main (String[] args) {
int n = 10;
if (args.length == 1)
n = Integer.parseInt(args[0]);
Testing t = new Testing (n);
t.print_f(Testing::f);
}
Run Code Online (Sandbox Code Playgroud)
...或者,f完全取消该方法,
t.print_f(i->2*i);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2276 次 |
| 最近记录: |