jdk8 lambda表达式list操作分组、过滤、求和、最值、排序、去重

java8的lambda表达式提供了一些方便list操作的方法,主要涵盖分组、过滤、求和、最值、排序、去重。跟之前的传统写法对比,能少写不少代码。

新建实体类

 1 package com.vvvtimes.vo;
 2  
 3 import java.math.BigDecimal;
 4 import java.util.Date;
 5  
 6 public class User {
 7  
 8     private Long id;
 9  
10     //姓名
11     private String name;
12  
13     //年龄
14     private int age;
15  
16     //工号
17     private String jobNumber;
18  
19     //性别
20     private String sex;
21  
22     //入职日期
23     private Date entryDate;
24  
25     //家庭成员数量
26     private BigDecimal familyMemberQuantity;
27  
28     public Long getId() {
29         return id;
30     }
31  
32     public void setId(Long id) {
33         this.id = id;
34     }
35  
36     public String getName() {
37         return name;
38     }
39  
40     public void setName(String name) {
41         this.name = name;
42     }
43  
44     public int getAge() {
45         return age;
46     }
47  
48     public void setAge(int age) {
49         this.age = age;
50     }
51  
52     public String getJobNumber() {
53         return jobNumber;
54     }
55  
56     public void setJobNumber(String jobNumber) {
57         this.jobNumber = jobNumber;
58     }
59  
60     public String getSex() {
61         return sex;
62     }
63  
64     public void setSex(String sex) {
65         this.sex = sex;
66     }
67  
68     public Date getEntryDate() {
69         return entryDate;
70     }
71  
72     public void setEntryDate(Date entryDate) {
73         this.entryDate = entryDate;
74     }
75  
76     public BigDecimal getFamilyMemberQuantity() {
77         return familyMemberQuantity;
78     }
79  
80     public void setFamilyMemberQuantity(BigDecimal familyMemberQuantity) {
81         this.familyMemberQuantity = familyMemberQuantity;
82     }
83 }

1.分组

通过groupingBy可以分组指定字段

1 //分组
2         Map<String, List<User>> groupBySex = userList.stream().collect(Collectors.groupingBy(User::getSex));
3         //遍历分组
4         for (Map.Entry<String, List<User>> entryUser : groupBySex.entrySet()) {
5             String key = entryUser.getKey();
6             List<User> entryUserList = entryUser.getValue();

 

2.过滤

通过filter方法可以过滤某些条件

1 //过滤
2         //排除掉工号为201901的用户
3         List<User> userCommonList = userList.stream().filter(a -> !a.getJobNumber().equals("201901")).collect(Collectors.toList());

 

3.求和

分基本类型和大数类型求和,基本类型先mapToInt,然后调用sum方法,大数类型使用reduce调用BigDecimal::add方法

1 //求和
2         //基本类型
3         int sumAge = userList.stream().mapToInt(User::getAge).sum();
4         //BigDecimal求和
5         BigDecimal totalQuantity = userList.stream().map(User::getFamilyMemberQuantity).reduce(BigDecimal.ZERO, BigDecimal::add);

 

上面的求和不能过滤bigDecimal对象为null的情况,可能会报空指针,这种情况,我们可以用filter方法过滤,或者重写求和方法

重写求和方法

 1 package com.vvvtimes.util;
 2  
 3 import java.math.BigDecimal;
 4  
 5 public class BigDecimalUtils {
 6  
 7     public static BigDecimal ifNullSet0(BigDecimal in) {
 8         if (in != null) {
 9             return in;
10         }
11         return BigDecimal.ZERO;
12     }
13  
14     public static BigDecimal sum(BigDecimal ...in){
15         BigDecimal result = BigDecimal.ZERO;
16         for (int i = 0; i < in.length; i++){
17             result = result.add(ifNullSet0(in[i]));
18         }
19         return result;
20     }
21 }

使用重写的方法

1 BigDecimal totalQuantity2 = userList.stream().map(User::getFamilyMemberQuantity).reduce(BigDecimal.ZERO, BigDecimalUtils::sum);

判断对象空

1 stream.filter(x -> x!=null)
1 stream.filter(Objects::nonNull)

判断字段空

1 stream.filter(x -> x.getDateTime()!=null)

4.最值

求最小与最大,使用min max方法

1 //最小
2         Date minEntryDate = userList.stream().map(User::getEntryDate).min(Date::compareTo).get();
3  
4         //最大
5         Date maxEntryDate = userList.stream().map(User::getEntryDate).max(Date::compareTo).get();

5.List 转map

1  /**
2          * List -> Map
3          * 需要注意的是:
4          * toMap 如果集合对象有重复的key,会报错Duplicate key ....
5          *  user1,user2的id都为1。
6          *  可以用 (k1,k2)->k1 来设置,如果有重复的key,则保留key1,舍弃key2
7          */
8         Map<Long, User> userMap = userList.stream().collect(Collectors.toMap(User::getId, a -> a,(k1,k2)->k1));

6.排序

可通过Sort对单字段多字段排序

1 //排序
2         //单字段排序,根据id排序
3         userList.sort(Comparator.comparing(User::getId));
4         //多字段排序,根据id,年龄排序
5         userList.sort(Comparator.comparing(User::getId).thenComparing(User::getAge));

7.去重

可通过distinct方法进行去重

1 //去重
2         List<Long> idList = new ArrayList<Long>();
3         idList.add(1L);
4         idList.add(1L);
5         idList.add(2L);
6         List<Long> distinctIdList = idList.stream().distinct().collect(Collectors.toList());

8.获取list某个字段组装新list

1 //获取list对象的某个字段组装成新list
2         List<Long> userIdList = userList.stream().map(a -> a.getId()).collect(Collectors.toList());

9.批量设置list列表字段为同一个值

1 addList.stream().forEach(a -> a.setDelFlag("0"));

转自:https://blog.csdn.net/qq_43563538/article/details/97912937

 

 1 import java.util.ArrayList;
 2 import java.util.List;
 3 
 4 public class Lambda {
 5     public static void main(String[] args) {
 6         List<String> list = new ArrayList<>();
 7         list.add("zhagnsan");
 8         list.add("wangwu");
 9         list.add("huanjin");
10         list.add("biali");
11 //增强for循环
12         for (String str : list) {
13             System.out.println(str);
14         }
15         System.out.println("---------------");
16         //第一种Lambda表达式
17         list.forEach((String string) -> {
18             System.out.println(string);
19         });
20         System.out.println("-------------------");
21         //由于只有一个参数,可以省略参数类型
22         list.forEach((str) -> {
23             System.out.println(str);
24         });
25         System.out.println("---------------------");
26         //由于只有一个参数,可以省略小括号,又由于只有一条语句,可以省略大括号,
27         list.forEach(string -> System.out.println(string));
28         System.out.println("---------------------");
29         //jdk8的新特性,双冒号是一种关键字
30         list.forEach(System.out::println);
31 
32     }
33 }

 

java8的lambda表达式提供了一些方便list操作的方法,主要涵盖分组、过滤、求和、最值、排序、去重。跟之前的传统写法对比,能少写不少代码。

新建实体类

package com.vvvtimes.vo;
 
import java.math.BigDecimal;
import java.util.Date;
 
public class User {
 
    private Long id;
 
    //姓名
    private String name;
 
    //年龄
    private int age;
 
    //工号
    private String jobNumber;
 
    //性别
    private String sex;
 
    //入职日期
    private Date entryDate;
 
    //家庭成员数量
    private BigDecimal familyMemberQuantity;
 
    public Long getId() {
        return id;
    }
 
    public void setId(Long id) {
        this.id = id;
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public int getAge() {
        return age;
    }
 
    public void setAge(int age) {
        this.age = age;
    }
 
    public String getJobNumber() {
        return jobNumber;
    }
 
    public void setJobNumber(String jobNumber) {
        this.jobNumber = jobNumber;
    }
 
    public String getSex() {
        return sex;
    }
 
    public void setSex(String sex) {
        this.sex = sex;
    }
 
    public Date getEntryDate() {
        return entryDate;
    }
 
    public void setEntryDate(Date entryDate) {
        this.entryDate = entryDate;
    }
 
    public BigDecimal getFamilyMemberQuantity() {
        return familyMemberQuantity;
    }
 
    public void setFamilyMemberQuantity(BigDecimal familyMemberQuantity) {
        this.familyMemberQuantity = familyMemberQuantity;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83

1.分组

通过groupingBy可以分组指定字段

        //分组
        Map<String, List<User>> groupBySex = userList.stream().collect(Collectors.groupingBy(User::getSex));
        //遍历分组
        for (Map.Entry<String, List<User>> entryUser : groupBySex.entrySet()) {
            String key = entryUser.getKey();
            List<User> entryUserList = entryUser.getValue();
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

2.过滤

通过filter方法可以过滤某些条件

        //过滤
        //排除掉工号为201901的用户
        List<User> userCommonList = userList.stream().filter(a -> !a.getJobNumber().equals("201901")).collect(Collectors.toList());
  • 1
  • 2
  • 3

3.求和

分基本类型和大数类型求和,基本类型先mapToInt,然后调用sum方法,大数类型使用reduce调用BigDecimal::add方法

        //求和
        //基本类型
        int sumAge = userList.stream().mapToInt(User::getAge).sum();
        //BigDecimal求和
        BigDecimal totalQuantity = userList.stream().map(User::getFamilyMemberQuantity).reduce(BigDecimal.ZERO, BigDecimal::add);
  • 1
  • 2
  • 3
  • 4
  • 5

上面的求和不能过滤bigDecimal对象为null的情况,可能会报空指针,这种情况,我们可以用filter方法过滤,或者重写求和方法

重写求和方法

package com.vvvtimes.util;
 
import java.math.BigDecimal;
 
public class BigDecimalUtils {
 
    public static BigDecimal ifNullSet0(BigDecimal in) {
        if (in != null) {
            return in;
        }
        return BigDecimal.ZERO;
    }
 
    public static BigDecimal sum(BigDecimal ...in){
        BigDecimal result = BigDecimal.ZERO;
        for (int i = 0; i < in.length; i++){
            result = result.add(ifNullSet0(in[i]));
        }
        return result;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

使用重写的方法

BigDecimal totalQuantity2 = userList.stream().map(User::getFamilyMemberQuantity).reduce(BigDecimal.ZERO, BigDecimalUtils::sum);

  • 1
  • 2

判断对象空

stream.filter(x -> x!=null)
  • 1
stream.filter(Objects::nonNull)
  • 1

判断字段空

stream.filter(x -> x.getDateTime()!=null)
  • 1

 

4.最值

求最小与最大,使用min max方法

        //最小
        Date minEntryDate = userList.stream().map(User::getEntryDate).min(Date::compareTo).get();
 
        //最大
        Date maxEntryDate = userList.stream().map(User::getEntryDate).max(Date::compareTo).get();
  • 1
  • 2
  • 3
  • 4
  • 5

5.List 转map

         /**
         * List -> Map
         * 需要注意的是:
         * toMap 如果集合对象有重复的key,会报错Duplicate key ....
         *  user1,user2的id都为1。
         *  可以用 (k1,k2)->k1 来设置,如果有重复的key,则保留key1,舍弃key2
         */
        Map<Long, User> userMap = userList.stream().collect(Collectors.toMap(User::getId, a -> a,(k1,k2)->k1));
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

6.排序

可通过Sort对单字段多字段排序

        //排序
        //单字段排序,根据id排序
        userList.sort(Comparator.comparing(User::getId));
        //多字段排序,根据id,年龄排序
        userList.sort(Comparator.comparing(User::getId).thenComparing(User::getAge));
  • 1
  • 2
  • 3
  • 4
  • 5

7.去重

可通过distinct方法进行去重

        //去重
        List<Long> idList = new ArrayList<Long>();
        idList.add(1L);
        idList.add(1L);
        idList.add(2L);
        List<Long> distinctIdList = idList.stream().distinct().collect(Collectors.toList());
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

8.获取list某个字段组装新list

        //获取list对象的某个字段组装成新list
        List<Long> userIdList = userList.stream().map(a -> a.getId()).collect(Collectors.toList());
  • 1
  • 2

9.批量设置list列表字段为同一个值

addList.stream().forEach(a -> a.setDelFlag("0"));
posted @ 2020-05-20 14:32  回青  阅读(43975)  评论(0编辑  收藏  举报