Java8 uses Lambda expressions (streaming) to quickly implement List to map, grouping, filtering and other operations

Using the new features of java8, some data processing can be realized with concise and efficient code.

1 Data preparation

1.1 Define a Fruit object

package com.wkf.workrecord.work;

import org.junit.Test;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * @author wuKeFan
 * @date 2023-03-09 15:07:04
 */
public class PublicTest {

    @Test
    public void test() {
        List<Fruit> appleList = new ArrayList<>();//存放apple对象集合
        Fruit apple1 =  new Fruit(1,"苹果1",new BigDecimal("3.25"),10);
        Fruit apple2 = new Fruit(1,"苹果2",new BigDecimal("1.35"),20);
        Fruit banana =  new Fruit(2,"香蕉",new BigDecimal("2.89"),30);
        Fruit lychee =  new Fruit(3,"荔枝",new BigDecimal("9.99"),40);
        appleList.add(apple1);
        appleList.add(banana);
        appleList.add(apple2);
        appleList.add(lychee);
    }

}

1.2 Add some test data

        List<Fruit> fruitList = new ArrayList<>();//存放水果对象集合
        Fruit apple1 =  new Fruit(1,"苹果1",new BigDecimal("3.25"),10);
        Fruit apple2 = new Fruit(1,"苹果2",new BigDecimal("1.35"),20);
        Fruit banana =  new Fruit(2,"香蕉",new BigDecimal("2.89"),30);
        Fruit lychee =  new Fruit(3,"荔枝",new BigDecimal("9.99"),40);
        fruitList.add(apple1);
        fruitList.add(banana);
        fruitList.add(apple2);
        fruitList.add(lychee);

2 text begins

2.1 Grouping

Map<Integer, List<Fruit>> groupBy = fruitList.stream().collect(Collectors.groupingBy(Fruit::getId));
System.err.println("groupBy:"+groupBy);

output:

groupBy:{1=[Fruit(id=1, name=苹果1, money=3.25, num=10), Fruit(id=1, name=苹果2, money=1.35, num=20)], 2=[Fruit(id=2, name=香蕉, money=2.89, num=30)], 3=[Fruit(id=3, name=荔枝, money=9.99, num=40)]}

2.2 List to Map

The id is the key, and the apple object is the value. You can do this:

/**
 * List -> Map
 * 需要注意的是:
 * toMap 如果集合对象有重复的key,会报错Duplicate key ....
 *  apple1,apple12的id都为1。
 *  可以用 (k1,k2)->k1 来设置,如果有重复的key,则保留key1,舍弃key2
 */
Map<Integer, Fruit> appleMap = fruitList.stream().collect(Collectors.toMap(Fruit::getId, a -> a,(k1,k2)->k1));
System.out.println(appleMap);

output:

{1=Fruit(id=1, name=苹果1, money=3.25, num=10), 2=Fruit(id=2, name=香蕉, money=2.89, num=30), 3=Fruit(id=3, name=荔枝, money=9.99, num=40)}

2.3 Filter

Filter out eligible elements from a collection:

//过滤出符合条件的数据
List<Fruit> filterList = fruitList.stream().filter(a -> a.getName().equals("香蕉")).collect(Collectors.toList());
System.err.println("filterList:"+filterList);

output:

filterList:[Fruit(id=2, name=香蕉, money=2.89, num=30)]

2.4 Summing

Sum the data in a collection by an attribute:

//计算 总金额
BigDecimal totalMoney = appleList.stream().map(Apple::getMoney).reduce(BigDecimal.ZERO, BigDecimal::add);
System.err.println("totalMoney:"+totalMoney);  //totalMoney:17.48

2.5 Find the maximum and minimum values ​​in the stream

Collectors.maxBy and Collectors.minBy to calculate the maximum or minimum value in the stream

Optional<Dish> maxDish = Dish.menu.stream().
      collect(Collectors.maxBy(Comparator.comparing(Dish::getCalories)));
maxDish.ifPresent(System.out::println);
 
Optional<Dish> minDish = Dish.menu.stream().
      collect(Collectors.minBy(Comparator.comparing(Dish::getCalories)));
minDish.ifPresent(System.out::println);

2.6 Deduplication

import static java.util.Comparator.comparingLong;
import static java.util.stream.Collectors.collectingAndThen;
import static java.util.stream.Collectors.toCollection;

List<Fruit> unique = fruitList.stream().collect(
    collectingAndThen(
    toCollection(() -> new TreeSet<>(comparingLong(Fruit::getId))), ArrayList::new)
);

3 The following table shows the static factory methods of the Collectors class

Guess you like

Origin blog.csdn.net/qq_37284798/article/details/129423483