banner
biuaxia

biuaxia

"万物皆有裂痕,那是光进来的地方。"
github
bilibili
tg_channel

java8 Quick Implementation of List to Map, Grouping, Filtering, and Other Operations

title: [Reprint] java8 Quick Implementation of List to Map, Grouping, Filtering, and Other Operations
date: 2021-11-01 11:29:00
toc: true
category:

  • Java
    tags:
  • Java
  • java8
  • Quick
  • Implementation
  • List
  • Conversion
  • Map
  • Grouping
  • Filtering
  • Operations

This article is a reprint from: java8 Quick Implementation of List to Map, Grouping, Filtering, and Other Operations_IT Xiaobai-CSDN Blog_java8 list to map


Using the new features of java8, you can use concise and efficient code to implement some data processing.

Define an Apple object:

public class Apple {
    private Integer id;
    private String name;
    private BigDecimal money;
    private Integer num;
    public Apple(Integer id, String name, BigDecimal money, Integer num) {
        this.id = id;
        this.name = name;
        this.money = money;
        this.num = num;
    }
}

Add some test data:

List<Apple> appleList = new ArrayList<>();//store a collection of apple objects
 
Apple apple1 =  new Apple(1,"Apple 1",new BigDecimal("3.25"),10);
Apple apple12 = new Apple(1,"Apple 2",new BigDecimal("1.35"),20);
Apple apple2 =  new Apple(2,"Banana",new BigDecimal("2.89"),30);
Apple apple3 =  new Apple(3,"Lychee",new BigDecimal("9.99"),40);
 
appleList.add(apple1);
appleList.add(apple12);
appleList.add(apple2);
appleList.add(apple3);

Grouping#

Group the objects in the List by a certain attribute, for example, group by id and put those with the same id together:

//Group List by ID, Map<Integer,List<Apple>>
Map<Integer, List<Apple>> groupBy = appleList.stream().collect(Collectors.groupingBy(Apple::getId));
 
System.err.println("groupBy:"+groupBy);
{1=[Apple{id=1, name='Apple 1', money=3.25, num=10}, Apple{id=1, name='Apple 2', money=1.35, num=20}], 2=[Apple{id=2, name='Banana', money=2.89, num=30}], 3=[Apple{id=3, name='Lychee', money=9.99, num=40}]}

List to Map#

Use id as the key and the apple object as the value, you can do it like this:

/**
 * List -> Map
 * Note that:
 * If the collection objects have duplicate keys, an error will be reported: Duplicate key ....
 * Both apple1 and apple12 have an id of 1.
 * You can use (k1, k2) -> k1 to keep key1 and discard key2 if there are duplicate keys.
 */
Map<Integer, Apple> appleMap = appleList.stream().collect(Collectors.toMap(Apple::getId, a -> a, (k1, k2) -> k1));

Print appleMap

{1=Apple{id=1, name='Apple 1', money=3.25, num=10}, 2=Apple{id=2, name='Banana', money=2.89, num=30}, 3=Apple{id=3, name='Lychee', money=9.99, num=40}}

Filtering#

Filter out elements from the collection that meet certain conditions:

//Filter out data that meets the conditions
List<Apple> filterList = appleList.stream().filter(a -> a.getName().equals("Banana")).collect(Collectors.toList());
 
System.err.println("filterList:"+filterList);
[Apple{id=2, name='Banana', money=2.89, num=30}]

Summation#

Sum the data in the collection based on a certain attribute:

//Calculate the total amount
BigDecimal totalMoney = appleList.stream().map(Apple::getMoney).reduce(BigDecimal.ZERO, BigDecimal::add);
System.err.println("totalMoney:"+totalMoney);  //totalMoney:17.48

Find the Maximum and Minimum Values in a Stream#

Use Collectors.maxBy and Collectors.minBy to calculate the maximum or minimum value in a 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);

Deduplication#

import static java.util.Comparator.comparingLong;
import static java.util.stream.Collectors.collectingAndThen;
import static java.util.stream.Collectors.toCollection;
 
// Deduplicate based on id
List<Person> unique = appleList.stream().collect(
                collectingAndThen(
                        toCollection(() -> new TreeSet<>(comparingLong(Apple::getId))), ArrayList::new)
        );
Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.