Java中Lambda表达式的使用

特别提示:本人博客部分有参考网络其他博客,但均是本人亲手编写过并验证通过。如发现博客有错误,请及时提出以免误导其他人,谢谢!欢迎转载,但记得标明文章出处:http://www.cnblogs.com/mao2080/

1、简介

  Lambda表达式是Java SE 8中一个重要的新特性。lambda表达式允许你通过表达式来代替功能接口。 lambda表达式就和方法一样,它提供了一个正常的参数列表和一个使用这些参数的主体(body,可以是一个表达式或一个代码块)。Lambda表达式还增强了集合库。 Java SE 8添加了2个对集合数据进行批量操作的包: java.util.function 包以及java.util.stream 包。 流(stream)就如同迭代器(iterator),但附加了许多额外的功能。 总的来说,lambda表达式和 stream 是自Java语言添加泛型(Generics)和注解(annotation)以来最大的变化。 在本文中,我们将从简单到复杂的示例中见认识lambda表达式和stream的强悍。

2、特点

λ表达式本质上是一个匿名方法,简洁,难懂,难以调试,维护人员想骂娘

3、基本语法

(parameters) -> expression
或
(parameters) ->{ statements; }

4、常用方法


package com.mao.com.lambda;

import java.util.*;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;


public class Test {

    public static void main(String[] args) {
        List<User> list = new ArrayList<>();
        list.add(new User("1", "张三", "一年级", 95));
        list.add(new User("2", "李四", "二年级", 96));
        list.add(new User("3", "王五", "三年级", 98));
        list.add(new User("4", "朱六", "三年级", 100));

        /**遍历*/
        list.forEach((o)->System.out.println("userId:"+o.getUserId()+", userName:"+o.getUserName()));

        /**遍历*/
        list.forEach(o->{
            System.out.println("userId:"+o.getUserId()+", userName:"+o.getUserName());
        });

        /**转hashSet*/
        Set<User> set1 = list.stream().collect(Collectors.toSet());

        /**转hashSet*/
        Set<String> set2 = list.stream().map(User::getUserName).collect(Collectors.toSet());

        /**转treeSet*/
        TreeSet<String> set3 = list.stream().map(User::getUserName).collect(Collectors.toCollection(TreeSet::new));

        /**转map*/
        Map<String, String> map1 = list.stream().collect(Collectors.toMap(User::getUserId, User::getUserName));

        /**转map*/
        Map<String, String> map2 = list.stream().collect(Collectors.toMap(User::getUserId, User::getUserName, (k1, k2)->k1));

        /**分组*/
        Map<String, List<User>> map3 = list.stream().collect(Collectors.groupingBy(User::getClassName));

        /**分组count*/
        Map<String, Long> map4 = list.stream().collect(Collectors.groupingBy(User::getClassName, Collectors.counting()));

        /**分组求和*/
        Map<String, Integer> map5 = list.stream().collect(Collectors.groupingBy(User::getClassName, Collectors.summingInt(User::getScore)));

        /**过滤条件*/
        List<User> temp1 = list.stream().filter(o->"1".equals(o.getUserId())).collect(Collectors.toList());

        /**多个过滤条件*/
        Predicate<User> scoFilter = (o) -> (o.getScore() > 25);
        Predicate<User> clsFilter = (o) -> ("三年级".equals(o.getClassName()));
        List<User> temp2 = list.stream().filter(scoFilter).filter(clsFilter).collect(Collectors.toList());

        /**取前多少个*/
        List<User> temp3 = list.stream().limit(2).collect(Collectors.toList());

        /**升序排序*/
        List<User> temp4 = list.stream().sorted(Comparator.comparing(User::getScore)).collect(Collectors.toList());
/**降序排序*/ List<User> temp5 = list.stream().sorted(Comparator.comparing(User::getScore).reversed()).collect(Collectors.toList());/**升序排序*/ User user1 = list.stream().max((u1, u2)->(u1.getScore()-u2.getScore())).get(); /**降序排序*/ User user2 = list.stream().min((u1, u2)->(u1.getScore()-u2.getScore())).get();
        /**并行计算*/
        Double average = users.parallelStream().filter(e -> e.getAge() > 5).mapToDouble(User::getAge).average().getAsDouble();
     /**求和*/
        int sum = list.parallelStream().mapToInt(p -> p.getScore()).sum();

        /**汇总数据*/
        IntSummaryStatistics stats = list.stream().mapToInt((x) -> x.getScore()).summaryStatistics();

        System.out.println("最大的数字 : " + stats.getMax());
        System.out.println("最小的数字 : " + stats.getMin());
        System.out.println("所有数字的总和 : " + stats.getSum());
        System.out.println("所有数字的平均值: " + stats.getAverage());

    }

    public static Set<Integer> getIntKeys(int sta, int size){
        return Stream.iterate(sta, item -> item+1).limit(size).collect(Collectors.toSet());
    }

}

 

 1 package com.mao.com.lambda;
 2 
 3 public class User{
 4 
 5     private String userId;
 6 
 7     private String userName;
 8 
 9     private String className;
10 
11     private int score;
12 
13     public User() {
14 
15     }
16 
17     public User(String userId, String userName, String className, int score) {
18         this.userId = userId;
19         this.userName = userName;
20         this.className = className;
21         this.score = score;
22     }
23 
24     public String getUserId() {
25         return userId;
26     }
27 
28     public void setUserId(String userId) {
29         this.userId = userId;
30     }
31 
32     public String getUserName() {
33         return userName;
34     }
35 
36     public void setUserName(String userName) {
37         this.userName = userName;
38     }
39 
40     public String getClassName() {
41         return className;
42     }
43 
44     public void setClassName(String className) {
45         this.className = className;
46     }
47 
48     public int getScore() {
49         return score;
50     }
51 
52     public void setScore(int score) {
53         this.score = score;
54     }
55 }

5、参考网站

https://www.cnblogs.com/franson-2016/p/5593080.html

posted @ 2018-08-11 18:26  mao2080  阅读(1758)  评论(1编辑  收藏  举报