什么是“ - >”在java中意味着

时间:2016-02-24 08:22:34

标签: java

我发现这个运算符登录java源代码这里是所有代码

/*
 * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 *
 */
package java.util.function;

/**
 * Represents an operation on a single operand that produces a result of the
 * same type as its operand.  This is a specialization of {@code Function} for
 * the case where the operand and result are of the same type.
 *
 * <p>This is a <a href="package-summary.html">functional interface</a>
 * whose functional method is {@link #apply(Object)}.
 *
 * @param <T> the type of the operand and result of the operator
 *
 * @see Function
 * @since 1.8
 */
@FunctionalInterface
public interface UnaryOperator<T> extends Function<T, T> {

    /**
     * Returns a unary operator that always returns its input argument.
     *
     * @param <T> the type of the input and output of the operator
     * @return a unary operator that always returns its input argument
     */
    static <T> UnaryOperator<T> identity() {
        return t -> t;
    }
}

我已经google搜索并在stackoverflow中搜索但没有找到任何内容,我想知道符号是什么 - &gt; 意味着

  

我发现了What does -> means in Java,但我不适合我

--------------------更新-----------------------

java -version
java version "1.8.0_66"
Java(TM) SE Runtime Environment (build 1.8.0_66-b18)
Java HotSpot(TM) 64-Bit Server VM (build 25.66-b18, mixed mode)

2 个答案:

答案 0 :(得分:2)

你看到的是一个Lambda表达式,这是Java 8中添加的一个新功能。

关于lambdas的说法太多了,但是简而言之,这是一个非常简洁的方法来添加一个只包含一个方法的匿名类。

您提到的方法在功能上等同于:

static <T> UnaryOperator<T> identity() {
    return new UnaryOperator<T>{
       public T apply(T parameter){
         return parameter;
       }
    }
}

完整的教程在这里:https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html

答案 1 :(得分:1)

一般语法是,

  

参数 - &gt;表达主体

使用lambda表达式,您可以引用最终变量或有效最终变量(仅分配一次)。

例如:

public class lambdatest{

   final static String firstmsg= "Hello! ";

   public static void main(String args[]){
      GreetingService greetService1 = message -> System.out.println(firstmsg+ message);
      greetService1.sayMessage("am here");
   }

   interface GreetingService {
      void sayMessage(String message);
   }
}
  

输出:你好!amhere

相关问题