Additional brackets in Java8 stream map() function

后端 未结 2 681
一个人的身影
一个人的身影 2021-01-15 22:51

I\'m working/testing streams in Java8 and come across very frustrating issue. I\'ve got the code which compiles well:

        List words = Arra         


        
2条回答
  •  有刺的猬
    2021-01-15 23:04

    According to the official Oracle tutorial

    A lambda expression consists of the following:

    A comma-separated list of formal parameters enclosed in parentheses. The CheckPerson.test method contains one parameter, p, which represents an instance of the Person class.

    Note: You can omit the data type of the parameters in a lambda expression. In addition, you can omit the parentheses if there is only one parameter. For example, the following lambda expression is also valid:

    p -> p.getGender() == Person.Sex.MALE 
        && p.getAge() >= 18
        && p.getAge() <= 25
    

    The arrow token, ->

    A body, which consists of a single expression or a statement block. This example uses the following expression:

    p.getGender() == Person.Sex.MALE 
        && p.getAge() >= 18
        && p.getAge() <= 25
    

    If you specify a single expression, then the Java runtime evaluates the expression and then returns its value. Alternatively, you can use a return statement:

    p -> {
        return p.getGender() == Person.Sex.MALE
            && p.getAge() >= 18
            && p.getAge() <= 25;
    }
    

    A return statement is not an expression; in a lambda expression, you must enclose statements in braces ({}). However, you do not have to enclose a void method invocation in braces. For example, the following is a valid lambda expression:

    email -> System.out.println(email)
    

    Since there is only one parameter in the provided lambda expression (x) -> x.toUpperCase() we can omit the parentheses: x -> x.toUpperCase(). String#toUpperCase returns a new String so there is no need to use return statement and braces. If instead we had a complex block with return statements we would have to enclose it into braces. Moreover in this case it is better to use Method Reference String::toUpperCase

    List wordLengths = words.stream().map(String::toUpperCase).collect(Collectors.toList()); 
    

提交回复
热议问题