Can you use Java Lambda expressions?

First look and then praise, give yourself some time to think. If it helps you, wechat search [program workplace] pays attention to this persistent workplace programmer.
What I have: Java skills, interview experience guidance, resume optimization, career planning guidance, skills improvement methods, endless career stories, personal growth experience.

 

 

 

 

This article is the 100th issue of original sharing

First look and then praise, give yourself some time to think. If it helps you, wechat search [program workplace] pays attention to this persistent workplace programmer.
What I have: Java skills, interview experience guidance, resume optimization, career planning guidance, skills improvement methods, endless career stories, personal growth experience.


Two days ago, someone asked me how much Lambda expressions were used. When I heard this, I knew that he seldom used them. After chatting, he said that he had hardly used them.

It is really a pity that Lambda expressions are not used in work. It is not only irresponsible for their own skills, but also pay little attention to project development.

In my opinion, the use of Lambda sometimes really reduces the development work of our programmers. At least learning that Lambda is also an attitude towards his yearning for technology. He can't keep away from new things (obviously Lambda is not new), which is even more unreasonable.

Let's talk about what I often use or have used here. If you don't feel satisfied, please check more sound materials as soon as possible to help you understand its concept, basic usage and the most commonly used cases.



01

concept

Speaking of Java 8, I am very familiar with java development. Although there are new versions, such as 10 and 12, many people are still using java 8.

Java 8 has added many new features: those interested can see the following (see the official website for more). Although JDK14 will be used later, these features are essential.

  • Lambda expressions − lambda allow functions to be passed as arguments to a method.

  • Method reference - method reference provides a very useful syntax, which can directly reference the methods or constructors of existing Java classes or objects (instances). Combined with lambda, method reference can make the language structure more compact and concise and reduce redundant code.

  • Default method - the default method is a method with an implementation in the interface.

  • New tools − new compilation tools, such as Nashorn engine jjs, class dependency analyzer jdeps.

  • Stream API - the newly added stream API (java.util.stream) introduces the true functional programming style into Java.

  • Date Time API − strengthen the processing of date and time.

  • Optional class − the optional class has become a part of the Java 8 class library to solve null pointer exceptions.

  • Nashorn allows us to run a javascript engine on a specific JVM.


Here is a link to the official website. Click to enter the interested partners. You can go to the official website to check
https://www.oracle.com/java/technologies/javase/8-whats-new.html

Today, let's talk about Lambda expressions.


02

Syntax, characteristics

To say another thing: Lambda expressions are very simple and convenient to use.

Let's first look at its syntax:

(parameters) -> expression
or

(parameters) ->{ statements;}

The syntax looks very simple. In fact, it is to replace anonymous inner classes with arrow expressions.

what? What do you mean by that? OK, let's take a look at some important features of expressions so that you can better understand them!

 

  • Optional type declaration: there is no need to declare parameter types, and the compiler can uniformly identify parameter values.

  • Optional parameter parentheses: one parameter does not need to define parentheses, but multiple parameters need to define parentheses.

  • Optional curly braces: if the body contains a statement, curly braces are not required.

  • Optional return keyword: if the body has only one expression return value, the compiler will automatically return the value. Braces need to specify that the expression returns a value.


After reading its features, whether you understand it, or whether it is clearer. If you already understand it, you need to look down and learn more about its use. If you don't understand.... Let's look down. As a program, wishing should have the spirit of beating the casserole to the end.

I believe that many people here have almost understood it. Some of the used ones have remembered what's going on. Let's explain it through a few small applications to better understand it.


03

Case explanation

 

1. Implementation of Runnable thread case

Use () - > {} instead of anonymous class:

//new Thread(new Runnable() before Java 8{    
@Override public void run() {        
System.out.println("Java8 Previous use");
}}).start();
//Java 8

new Thread( () -> System.out.println("Java8 Use in") ).start();
1. If the method is only output, it can be simpler to Ctrip:

() -> System.out.println("Hello Lambda Expressions");

2. If the method accepts two parameters, as follows:

(int even, int odd) -> even + odd

 

 

2. Realize event handling

 

Lambda Implement event listener, using Lambda Expression instead of anonymous class.
// Before Java 8

JButton show = new JButton("Show");

show.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Java 8 before");
}     
});

// Java 8 show.addActionListener((e) -> {
System.out.println("Java 8 ");});


3. Use Lambda expression to traverse the List set

//Before Java 8, list features = arrays Aslist ("program workplace 1", "program workplace 2", "program workplace 3", "program workplace 4");
for (String feature : features) {
System.out.println(feature);}

//Java 8:List features = Arrays. Workplace procedures ("workplace procedures", "AS3");
features.forEach(n -> System.out.println(n));
features.forEach(System.out::println);

Output:Program workplace 1 program workplace 2 program workplace 3 program workplace 4
I often use the forEach expression, which is much more convenient than traversing the array through the for loop.

Note: the method reference uses two colons:: this operation symbol.

4. Use Lambda expression and function interface

Java 8 adds a new package Java util. Function, which has an interface java util. function. Predicate supports Lambda function programming:

public static void main(args[]){List languages = Arrays.asList("Java", "Scala", "C++", "Haskell", "Lisp");
System.out.println("Languages which starts with J :");filter(languages, (str)->str.startsWith("J"));
System.out.println("Languages which ends with a ");filter(languages, (str)->str.endsWith("a"));
System.out.println("Print all languages :");filter(languages, (str)->true);
System.out.println("Print no language : ");filter(languages, (str)->false);
System.out.println("Print language whose length greater than 4:");filter(languages, (str)->str.length() > 4);}
public static void filter(List names, Predicate condition) {for(String name: names) {if(condition.test(name)) {System.out.println(name + " ");
}
}
}}
Output:Languages which starts with J :JavaLanguages which ends with aJavaScalaPrint all languages :JavaScalaC++HaskellLispPrint no language :
Print language whose length greater than 4:ScalaHaskell
//Even betterpublic static void filter(List names, Predicate condition) { names.stream().filter((name) -> (condition.test(name)))
.forEach((name) -> {System.out.println(name + " ");
});
}

This can be used to read the specified string and location information in the collection.

5. Create a collection of strings through filtering

Filtering is a general operation for large Collection operations. Stream provides a filter() method and accepts a Predicate object, which means that you can transfer lambda expressions into this method as a filtering logic:

//Create a list of strings longer than 2 characters

List<String> filtered = strList.stream().filter(x -> x.length()> 2) .collect(Collectors.toList());

System.out.printf("Original List : %s, filtered list : %s %n", strList, filtered);Output :Original List : [abc, , bcd, , defg, jk], filtered list [abc, bcd, defg]


6. Apply functions to each element in the set. We often need to apply certain functions to the elements in the set, such as multiplying or dividing each element in the table by a value, etc

// Convert String to Uppercase and join them using comaList<String> G7 = Arrays.asList("USA", "Japan", "France", "Germany","Italy", "U.K.","Canada");

String G7Countries = G7.stream().map(x -> x.toUpperCase()) .collect(Collectors.joining(", "));

System.out.println(G7Countries);Output :USA, JAPAN, FRANCE, GERMANY, ITALY, U.K., CANADA

The above is to convert strings to uppercase and then string them with commas.

 

7. Create a sublist by copying different values

Use the distinct() method of Stream to filter the duplicate elements in the collection.

// Create List of square of all distinct numbersList<Integer> numbers = Arrays.asList(9, 10, 3, 4, 7, 3, 4);
List<Integer> distinct = numbers.stream().map( i -> i*i).distinct().collect(Collectors.toList());
System.out.printf("Original List : %s, Square Without duplicates :  %s %n", numbers, distinct);Output :Original List : [9, 10, 3, 4, 7, 3, 4],
Square Without duplicates : [81, 100, 9, 16, 49]
//Get count, min, max, sum, and average for numbers10.
calculation List The maximum, minimum, sum and average values of the elements in
List<Integer> primes = Arrays.asList(2, 3, 5, 7, 11, 13, 17, 19, 23, 29);IntSummaryStatistics stats = primes.stream().mapToInt((x) -> x) .summaryStatistics();
System.out.println("Highest prime number in List : "+ stats.getMax());System.out.println("Lowest prime number in List : "+ stats.getMin());
System.out.println("Sum of all prime numbers : "+ stats.getSum());System.out.println("Average of all prime numbers : "+ stats.getAverage());
Output : Highest prime number in List : 29Lowest prime number in List : 2Sum of all prime numbers : 129Average of all prime numbers : 12.9


Github (code cloud Gitee synchronization) https://github.com/ProceduralZC/JavaDevGuide/tree/master/code/JavaBasic Included, welcome star.

 

I am a dedicated professional programmer in Erdong bimonthly. Wechat search [program workplace] pays attention to me. Don't forget to connect for three times. You can like, collect and leave messages at will. I won't choose.
Zhihu No.: Procedure
Workplace program: CSDN
Note: if there are any questions in the article, you are welcome to correct them mercilessly.

Posted by foolygoofy on Thu, 19 May 2022 11:38:20 +0300