What is a lambda expression
1. Functional interfaces
Before we get to lambda expressions, we have to mention functional interfaces: an interface that contains only one method is a functional interface. Such as:
public class LambdaTest { public static void main(String[] args) { Lambda lambda=new SonLambda(); lambda.say(); Lambda {void say(); Lambda {void say(); } //2. A class implements the interface, Class SonLambda implements Lambda {@override public void say() {system.out.println (" I love Lambda "); }}Copy the code
Sometimes if we’re too lazy we’ll just write an anonymous inner class.
public class LambdaTest { public static void main(String[] args) { //2. Lambda Lambda =new Lambda() {@override public void say() {system.out.println (" I like Lambda "); }}; lambda.say(); Lambda {void say(); Lambda {void say(); }Copy the code
But surely the lazier (and simpler) code we can write is the better, and that’s where Lambda expressions come in.
Lambda expressions are one of the most important new features released in Java8. They are designed to solve the problem of anonymous inner class code and make code look cleaner.
The syntax of a lambda expression is as follows:
(parameters) -> expression
或者
(parameters) ->{ statements;}
Copy the code
Parameters are parameters, expression is expression.
How do we represent the anonymous inner class in the above example in Lambda expressions?
Because the anonymous inner class in the example above has only one method, we can omit its interface name and method name.
Since there are no arguments, we can simply use a parenthesis to indicate the method name and use -> to refer to the method body. As shown below :() -> {} replaces anonymous inner classes.
public class LambdaTest { public static void main(String[] args) { Lambda lambda=()->{ System.out.println("i like lombda"); }; lambda.say(); Lambda {void say(); Lambda {void say(); }Copy the code
So how, you might ask, should an interface with arguments be represented in lambda expressions?
As follows:
public class LambdaTest { public static void main(String[] args) { Lambda lambda=(a,b)->{ System.out.println("a="+a+" b="+b); }; Lambda. Say (1, 2); Lambda {void say(int a,int b); Lambda {void say(int a,int b); }Copy the code
02. Common methods for Lambda expressions
1. ForEach traverses the elements of the collection
List<String> fruits= Arrays.asList("apple", "orange", "banana"); Fruits. ForEach (fruit->{System. Out. Println (" fruit: "+fruit); });Copy the code
2. The stream flow
Stream in Java8 is a collection enhancement that focuses on doing all sorts of very convenient, efficient aggregation operations on collections, or bulk data operations.
3. map()
Gets an element of the collection and returns a new collection. Remember to get the stream of the collection before using the map.
Public class LambdaTest {public static void main(String[] args) {ArrayList<User> list = new ArrayList<>(); List. add(new User(1," zhang Wuji ",25)); List. add(new User(2," zhao Min ",24)); List. add(new User(3," zhou Zhizhu ",23)); List<String> nameList = list.stream().map(User::getName).collect(Collectors. ToList ()); ForEach (name->{system.out.println (" name: "+name); }); }}Copy the code
4. collect(Collector c)
By converting the result of the operation to a collection, the Collector can be converted to a list as well as a set, which is a non-repeating collection.
Public class LambdaTest {public static void main(String[] args) {ArrayList<User> list = new ArrayList<>(); List. add(new User(1," zhang Wuji ",25)); List. add(new User(2," zhang Wuji ",24)); List. add(new User(3," zhou Zhizhu ",23)); // Get all the names of the Collectors Set<String> Set = list.stream().map(User::getName).collect(Collectors. ToSet ()); ForEach (name->{system.out.println (" not duplicate name: "+name); }); }}Copy the code
5. Distinct () to heavy
Public class LambdaTest {public static void main(String[] args) {ArrayList<User> list = new ArrayList<>(); List. add(new User(1," zhang Wuji 01",25)); List. add(new User(2," zhang Wuji 01",24)); List. add(new User(3," zhao Min ",23)); List<String> nameList = list.stream().map(User::getName).distinct().collect(Collectors. ToList ()); Namelist. forEach(name->{system.out.println (" name = "+name); }); }}Copy the code
6. The reduce () :
Concatenate values in elements in some way, and aggregate functions in SQL such as sum(), AVg (), or count() are actually reduce operations because they accept multiple values and return a single value.
Public class LambdaTest {public static void main(String[] args) {ArrayList<User> list = new ArrayList<>(); List. add(new User(1," zhang Wuji ",25)); List. add(new User(2," zhou Zhizhu ",24)); List. add(new User(3," zhao Min ",23)); Map (w -> w.gettage ()); map(w -> w.gettage ()); map(w -> w.gettage ()); map(w -> w.gettage ()); Integer sumAge = list.stream().map(w -> w.gettage ()).reduce((x, w -> w.gettage ()).reduce((x, w -> w.gettage ()).reduce((x, w -> w.gettage ()). y) -> x + y).get(); System.out.println(" sum of three ages: "+sumAge); }}Copy the code
7. The match usage
AllMatch () : Checks if all elements match
AnyMatch (): Checks whether any element is matched
NoneMatch (): Checks if there are no matching elements
Public class LambdaTest {public static void main(String[] args) {ArrayList<User> list = new ArrayList<>(); List. add(new User(1," zhang Wuji ",25)); List. add(new User(2," zhou Zhizhu ",24)); List. add(new User(3," zhao Min ",23)); boolean result01 = list.stream().allMatch(w->w.getAge()>23); boolean result02= list.stream().anyMatch(w->w.getAge()>23); boolean result03= list.stream().noneMatch(w->w.getAge()>23); System.out.println(" Is everyone older than 23? : "+ result01); System.out.println(" Is there anyone older than 23? : "+ result02); System.out.println(" Aren't they older than 23? : "+ result03); }}Copy the code
8. Filter () Condition filtering
Public static void main(String[] args) {ArrayList<User> list = new ArrayList<>(); List. add(new User(1," zhang Wuji ",25)); List. add(new User(2," zhou Zhizhu ",24)); List. add(new User(3," zhao Min ",23)); / / 1. Filter (w - > w.g etAge () > 23) older than 23 / / 2. The map (w - > w.g etName ()) to obtain the name of the person / / 3. Access to these three people older than 23 of the name of the person who set a List < String > nameList = List. The stream () filter (w - > w.g etAge () > 23). The map (w - > w.getName()).collect(Collectors.toList()); ForEach (name->{system.out.println (" age > 23: "+name); }); }Copy the code
9. Sorted ()
Public static void main(String[] args) {ArrayList<User> list = new ArrayList<>(); List. add(new User(1," zhang Wuji ",25)); List. add(new User(2," zhou Zhizhu ",24)); List. add(new User(3," zhao Min ",23)); //1. Sorted by a field (Comparator.comparing(User::getAge)) //2. Reversed () sort the List<User> users1 = list.stream().sorted(Comparator.comparing(User::getAge)).collect(Collectors.toList()); System.out.println("------------- sort from youngest to oldest "); users1.forEach(user->{ System.out.println(user.getName()+" "+user.getAge()); }); System.out.println("------------- sort from oldest to youngest "); List<User> users2 = list.stream().sorted(Comparator.comparing(User::getAge).reversed()).collect(Collectors.toList()); users2.forEach(user->{ System.out.println(user.getName()+" "+user.getAge()); }); }Copy the code
03. Common examples of Lambda expressions
1. Case 1: Obtain the ids of all users.
List<Integer> ids = list.stream().map(w -> w.getId()).collect(Collectors.toList());
Copy the code
2. Case 2: Put all user ids as keys and names as values into a map.
Map<Integer, String> userMap = list.stream().collect(Collectors.toMap(User::getId,User::getName));
Copy the code
3. Case 3: Using stream to convert collections, we no longer need to add one by one.
List<User> users = Stream.of(user1, user2, user3).collect(Collectors.toList());
Copy the code
4. Case 4: Map object conversion. We usually check data from the database as PO object and return it to the Web end as VO object, which involves object conversion and return, and Map provides convenient operation.
List<UserVo> userVos = userList.stream().map(user -> {
UserVo userVo = new UserVo();
BeanUtils.copyProperties(user, userVo);
return userVo;
}).collect(Collectors.toList());
Copy the code
5. Case 5: Group by a certain attribute, for example, here we group by user gender.
Map<Integer, List<User>> genderGroup = userList.stream().collect(Collectors.groupingBy(User::getSex, Collectors.toList()));
Copy the code
6. Case 6: Finding minimum, maximum, average, and Sum.
int min = userList.stream().mapToInt(User::getAge).min().orElse(-1);
int max = userList.stream().mapToInt(User::getAge).max().orElse(-1);
int sum = userList.stream().mapToInt(User::getAge).sum();
double average = userList.stream().mapToInt(User::getAge).average().orElse(-1);
Copy the code
04. Write to the end
Note: A constraint on lambda expressions is that only final or final local variables can be referenced. This means that variables defined outside the domain cannot be modified inside the lambda or an error will be reported.
The article continues to update, wechat search “Eclipse programming” the first time to read. Reply keywords have surprise!!