lambda expression grouping, filtering, summation, maximum, sorting, de-duplication

Keywords: Java Lambda less

Article directory

brief introduction

New features of Java 8

java8's lambda expression provides some convenient methods for list operation, mainly including grouping, filtering, summation, maximum value, sorting and de duplication. Compared with the traditional way of writing, it can write a lot less code.


Prepare an entity class first

import java.math.BigDecimal;
import java.util.Date;
public class User {
    private long id;
    //Full name
    private String name;
    private int age;
    //Job number
    private String jobNumber;
    private int gender;
    //Date of entry
    private Date entryDate;
    private BigDecimal money;

    //Omit get set


Grouping Collections into Multiple Collections by Grouping By

//Get a Map Set with Age as the Key and User Set as the Value by Age Grouping
Map<Integer,List<User>> groupByAge =,collect(Collectors.groupingBy(User::getAge));


Some conditions can be filtered by filter method

//Exclude users with work number 1001
//Instances that add conditions to filter and retain return true
List<User> list = -> !user.getJobNumber().equals("1001")).collect(Collectors.toList());


The basic type first mapToInt, then call the sum method, and the large number type calls the BigDecimal::add method with reduce.

//Basic types
int sumAge =;
//BigDecimal summation
BigDecimal totalMoney=, BigDecimal::add);

Note: If the object is null, a null pointer exception will be thrown in the summation of the BigDecimal type mentioned above.

1. We can try filter first.

//First filter out null
List<Usrt> list = -> null != user).collect(Collectors.toList());
//Re summation
BigDecimal totalMoney =,BigDecimal::add);

2. Or you can rewrite the summation method

package com.jamesluozhiwei.util;
import java.math.BigDecimal;
public class BigDecimalUtils {
 	 * If null, return 0
 	 * @param in
 	 * @return
    public static BigDecimal ifNullSet0(BigDecimal in) {
        if (in != null) {
            return in;
        return BigDecimal.ZERO;
 	 * Summation
 	 * @param in
 	 * @return
    public static BigDecimal sum(BigDecimal{
        BigDecimal result = BigDecimal.ZERO;
        for (int i = 0; i < in.length; i++){
            result = result.add(ifNullSet0(in[i]));
        return result;


After rewriting the summation method

//Summation by rewriting
BigDecimal totalMoney =,BigDecimalUtils::sum);

Maximum value

The min max method is used to find the maximum and minimum values.

Date minEntryDate =;
Date maxEntryDate =;

List to Map

    * List -> Map
    * It should be noted that:
    * toMap If the collection object has a duplicate key, Duplicate key... will be missed.
    * user1,user2 The id is 1.
    * You can use (k1, k2) - > K1 to set it up. If there are duplicate keys, keep key1 and discard key2.
    Map<Long, User> userMap =, user -> user,(k1,k2)->k1));


Sort can be used to sort single field and multiple fields

//Single field sorting, sorted by id
//Multi-field sorting, by id, by age

Duplicate removal

De-duplication by distinct method

//Duplicate removal
List<Long> idList = new ArrayList<Long>();
List<Long> distinctIdList =;

Get a list object, a field, and assemble a new list

//Get a field of the list object and assemble it into a new list
List<Long> userIdList = -> a.getId()).collect(Collectors.toList());

Batch setting list list list list field to the same value -> a.setMoney("0"));

Posted by Kingskin on Thu, 10 Oct 2019 04:02:11 -0700