【问题标题】:Need help understanding symbol "->" in Java需要帮助理解 Java 中的符号“->”
【发布时间】:2015-07-07 10:26:44
【问题描述】:

需要帮助理解 Java 中的符号 ->。 Google 和 Stack Overflow 搜索均未返回任何结果。有人可以分享一些链接以了解它是如何工作的或解释下面的代码示例:

@SpringBootApplication
public class Application {

    @Bean
    CommandLineRunner commandLineRunner(PersonRepository personRepository) {
        return args -> {
            Arrays.asList("Phil", "Josh").forEach(name ->
                personRepository.save(new Person(name, (name + "@email.com").toLowerCase()))
            );
            personRepository.findAll().forEach(System.out::println);
        };
    }

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

【问题讨论】:

  • 搜索 java 8 lambda 表达式

标签: java symbols


【解决方案1】:

在 Java 8 中支持 Lambda 表达式。

一个 lambda 表达式具有以下语法特征。

            parameter -> expression body.

考虑以下示例

   //with type declaration
  MathOperation addition = (int a, int b) -> a + b;

  //with out type declaration
  MathOperation subtraction = (a, b) -> a - b;

  //with return statement along with curly braces
  MathOperation multiplication = (int a, int b) -> { return a * b; };
  //without return statement and without curly braces
  MathOperation division = (int a, int b) -> a / b;

  System.out.println("10 + 5 = " + tester.operate(10, 5, addition));       
  System.out.println("10 - 5 = " + tester.operate(10, 5, subtraction));
  System.out.println("10 x 5 = " + tester.operate(10, 5, multiplication));
  System.out.println("10 / 5 = " + tester.operate(10, 5, division));

参考Lamba expressions Java8

【讨论】:

    【解决方案2】:

    这种方法的简单示例

    public class Main {
    
        @FunctionalInterface
        interface NiceInterface {
            void run(String[] args);
        }
    
        public static void main(String[] args) {
    
            NiceInterface myNice = myArgs -> {
                for (String myArg : myArgs) {
                    System.out.println(myArg);
                }
            };
    
            myNice.run(new String[]{"aaa", "bbb"});
            //aaa
            //bbb
    
            myNice = getOtherNice();
    
            myNice.run(new String[]{"111", "222", "333"});
            //111222333
        }
    
        private static NiceInterface getOtherNice() {
            return args -> {
                StringBuilder sb = new StringBuilder();
                for (String myArg : args) {
                    sb.append(myArg);
                }
    
                System.out.println(sb.toString());
            };
        }
    }
    

    【讨论】:

    • 如果方法没有参数,那么只使用空括号 () -> { }
    猜你喜欢
    • 2020-02-22
    • 1970-01-01
    • 1970-01-01
    • 2013-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-10
    相关资源
    最近更新 更多