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.

Example

Prepare an entity class first

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

    //Omit get set
    ...
 
}

Grouping

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 = userList.stream(),collect(Collectors.groupingBy(User::getAge));

filter

Some conditions can be filtered by filter method

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

Summation

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

//Summation
//Basic types
int sumAge = userList.stream().mapToInt(User::getAge).sum();
//BigDecimal summation
BigDecimal totalMoney= userList.stream().map(User::getMoney).reduce(BigDecimal.ZERO, 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 = userList.stream().filter(user -> null != user).collect(Collectors.toList());
//Re summation
BigDecimal totalMoney = userList.stream().map(User::getMoney).reduce(BigDecimal.ZERO,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 ...in){
        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 = userList.stream().map(User::getMoney).reduce(BigDecimal.ZERO,BigDecimalUtils::sum);

Maximum value

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

//Minimum
Date minEntryDate = userList.stream().map(User::getEntryDate).min(Date::compareTo).get();
//Maximum
Date maxEntryDate = userList.stream().map(User::getEntryDate).max(Date::compareTo).get();

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 = userList.stream().collect(Collectors.toMap(User::getId, user -> user,(k1,k2)->k1));

sort

Sort can be used to sort single field and multiple fields

//sort
//Single field sorting, sorted by id
userList.sort(Comparator.comparing(User::getId));
//Multi-field sorting, by id, by age
userList.sort(Comparator.comparing(User::getId).thenComparing(User::getAge));

Duplicate removal

De-duplication by distinct method

//Duplicate removal
List<Long> idList = new ArrayList<Long>();
idList.add(1L);
idList.add(1L);
idList.add(2L);
List<Long> distinctIdList = idList.stream().distinct().collect(Collectors.toList());

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 = userList.stream().map(a -> a.getId()).collect(Collectors.toList());

Batch setting list list list list field to the same value

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

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