The existing case of lambda parameters

When you write a lambda expression, you can define multiple parameters. The following are some examples of lambdas that define single or multiple parameters:

key -> key.uppercase();           // single lambda parameter

(int x, int y) -> x > y? x : y; // two lambda parameters

(a, b, c, d) -> a + b + c + d; // four lambda parameters

Let's use one of the lambdas from the preceding code in stream processing. The following example will provide the string values from List as output, in uppercase:

List<String> talks = List.of("Kubernetes", "Docker", "Java 11");
talks.stream()
.map(key -> key.toUpperCase())
.forEach(System.out::prinltn);

So far, so good. But what happens if the preceding code is defined in a method (say, process()) with a local variable (say, key (code on line number 3)) that overlaps with the name of the key  lambda parameter (defined and used on the line number 5)? See the following code:

1. void process() {
2. List<String> talks = List.of("Kubernetes", "Docker", "Java 11");
3. String key = "Docker"; // local variable key
4. talks.stream()
5. .map(key -> key.toUpperCase()) // WON'T compile: 'key'
redefined
6. .forEach(System.out::prinltn);
7. }

At present, the preceding code won't compile, because the key variable used in the lambda expression for the map() method can't overshadow the local key variable, defined in the process() method. 

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.139.83.199