【问题标题】:Confused about the lambda expression对 lambda 表达式感到困惑
【发布时间】:2015-05-24 16:20:30
【问题描述】:

我正在阅读一个示例代码,该代码是添加一个 10 像素宽的灰色框架,通过使用 lambda 表达式调用它来替换图像边框上的像素:

public static Image transform(Image in, ColorTransformer t) {
    int width = (int) in.getWidth();
    int height = (int) in.getHeight();
    WritableImage out = new WritableImage(width, height);
    for (int x = 0; x < width; x++) {
        for (int y = 0; y < height; y++) {
            out.getPixelWriter().setColor(x, y,
                    t.apply(x, y, in.getPixelReader().getColor(x, y)));
        }
    }
    return out;
}

@Override
public void start(Stage stage) throws Exception {
    Image image = new Image("test_a.png");
    Image newImage = transform(
                       image,
                       (x, y, c) -> (x <= 10 || x >= image.getWidth() - 10 || 
                                     y <= 10 || y >= image.getHeight() - 10) 
                                     ? Color.WHITE : c
                     );
        stage.setScene(new Scene(new VBox(
     new ImageView(image),
     new ImageView(newImage))));
  stage.show();
    stage.show();
 }
}

@FunctionalInterface
interface ColorTransformer {
    Color apply(int x, int y, Color colorAtXY);
}

我对 lambda 表达式感到困惑:

Image newImage = transform(
                   image,
                   (x, y, c) -> (x <= 10 || x >= image.getWidth() - 10 || 
                                 y <= 10 || y >= image.getHeight() - 10) 
                                 ? Color.WHITE : c
                 );
  1. 给图形加边框,我觉得“&&”应该比“||”更合理。但是,“&&”在这里不起作用!谁能解释一下?

  2. 我不太明白“?Color.WHITE : c”。首先,为什么它们在前一个括号之外?其次,问号(?)是什么意思?

提前感谢您的帮助。

【问题讨论】:

  • 您的问题/问题不在于 lambda,而在于 conditional operator 的逻辑。
  • 谢谢~我学到了一些东西。 :-)

标签: java


【解决方案1】:

首先,您的问题与lambda 无关,而是一般的表达。

从第二部分开始:A ? B : C 意思是“如果A被认为是真的,我的值是 B 否则它是 C。一种if 表达式内的语句。

至于第一部分:如果 任何 个测试为真(每个测试的形式为 the point is too far left/right/up/down),那么这个点(大概)在外面,并且是白色的;否则,使用颜色c。你不能同时让它们都为真:例如,一个点不能既太左又太右。

【讨论】:

  • 非常感谢您的评论。我很清楚这一点。只是一个问题:代码根本没有定义“c”,因此,如果条件为FALSE,系统将如何获得“c”的值?
  • 一个关于lambda的问题; (x, y, c) 是您的 lambda 的参数列表,因此 cxy 正在通过调用此匿名函数获取它们的值。
【解决方案2】:

你的程序相当于这样:(如果你不使用 lambda)

public static Image transform(Image in) {
    int width = (int) in.getWidth();
    int height = (int) in.getHeight();
    WritableImage out = new WritableImage(width, height);
    for (int x = 0; x < width; x++) {
        for (int y = 0; y < height; y++) {
            Color c = in.getPixelReader().getColor(x, y);
            if (x <= 10 || x >= image.getWidth() - 10 || 
                y <= 10 || y >= image.getHeight() - 10) 
                c = Color.WHITE;
          /* else
                c = c; */
             out.getPixelWriter().setColor(x, y, c);
         }
    }
    return out;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-03-01
    • 1970-01-01
    • 2018-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多