In Lambda Expressions (Java), how is an expression without using a parameter?

As I know, there are 3 kinds of jamba java expressions.

  • (int x, int y) -> { return x + y; }
  • x -> x * x
  • ( ) -> x

The third seems to never be used.

Could you give an example for each of the three cases (an additional example for case 3 would be good) to illustrate their use? Please make them as simple as possible (preferably starting with list.stream () ....)

+5
source share
3 answers
  • The first expression will be used when you get 2 parameters for the method and return the value.

  • The second expression will be used x -> x * x , where you get 1 parameter for the method and return the value.

  • The third expression ( ) -> x will be used ( ) -> x , where you get 0 parameters for the method and return the value.

Take the third one. Suppose you have an interface that takes no parameters and returns a value.

 static interface RandomMath { public int random(); } 

Now you want to instantiate this interface along with its implementation. This will usually be done below: -

 Random random = new Random(); RandomMath randomMath = new RandomMath() { @Override public int random() { return random.nextInt(); } }; 

Using lamda will look like this: -

 Random random = new Random(); RandomMath randomMath = () -> random.nextInt(); //the third type. 

Similarly, for the first two, it can be used for methods that take two and one parameters and return a value.

 static interface PlusMath { public int plus(int a, int b); } PlusMath plusMath = (a, b) -> a + b; static interface SquareMath { public int square(int a); } SquareMath squareMath = a -> a * a; 
+5
source

The first two examples are different from the previous ones. Variables in a function (lambda expression) relate to its parameters.

In the third example, x refers to a variable outside the lambda expression, but within the lexical domain (it can be either a local variable from a method or an instance variable).

Example 1 (usually a reduction in flow) calculates the sum by passing the calculated sum and the next element from the list to the lambda function:

  int sum = list.stream().reduce((int x, int y) -> x+y); 

Example 2, calculates the squares of the elements:

  squares = list.stream().map((int x) -> x*x).collect(Collectors.toList()); 

Example 3, sets the default value of an element if it is null in the list:

  final int x = MY_DEFAULT_VALUE; // lambda refers the the variable above to get the default defaults = list.stream().map((Integer v) -> v != null ? v : x); 

Or better, for example, 3 are atomic map methods:

  int x = MY_DEFAULT_VALUE; // lambda refers the the variable above to get the default map.computeIfAbsent(1, (Integer key) -> x); // the same could be achieved by putIfAbsent() of course // but typically you would use (Integer key) -> expensiveComputeOfValue(x) // ... // or quite common example with executor public Future<Integer> computeAsync(final int value) { // pass the callback which computes the result synchronously, to Executor.submit() // the callback refers to parameter "value" return executor.submit(() -> computeSync(value)); } 
+4
source

Before moving on to the examples below, first note that Lambda expressions can be written for any SAM interfaces (also called functional) (Infact, Lambda expression - syntactic sugar > to replace a detailed anonymous class (with a single method) in Java).

The interface of a single abstract method or a functional interface is an interface that contains only one abstract method), you can see here . If you know this simple point, you can write (play with) any number of your own functional interfaces, and then write various lambda expressions according to each of these functional interface methods.

The examples below are written using existing JDK (1.8) functional interfaces, such as Callable , Function , BiFunction (Similarly, there are many built-in functional interfaces in JDK 1.8, in most cases they meet our requirements ).

(1) Example for (int x, int y) β†’ {return x + y; }

 //Below Lamda exp, takes 2 Input int Arguments and returns string BiFunction<Integer, Integer, String> biFunction = (num1, num2) -> "Sum Is:" +(num1 + num2); System.out.println(biFunction.apply(100, 200)); 

(2) Example for x β†’ x * x

 //Below Lamda exp, takes string Input Argument and returns string list.stream().map((String str1) -> str1.substring(0, 1)). forEach(System.out::println); 

(3) Example for () β†’ x

 //Below Lambda exp, Input argument is void, returns String Callable<String> callabl = () -> "My Callable"; ExecutorService service = Executors.newSingleThreadExecutor(); Future<String> future = service.submit(callable); System.out.println(future.get()); 
+3
source

Source: https://habr.com/ru/post/1260378/


All Articles