Using Java 8 Streams for List‑to‑Map, Grouping, Filtering, Summing, and Deduplication

This tutorial shows how to use Java 8 Stream API to convert a List of objects into a Map, group elements by a key, filter by condition, calculate aggregates such as sum, find max/min values, and remove duplicates, all with concise functional code.

Architect's Tech Stack
Architect's Tech Stack
Architect's Tech Stack
Using Java 8 Streams for List‑to‑Map, Grouping, Filtering, Summing, and Deduplication

This article demonstrates how to leverage Java 8 Stream API to efficiently transform a List of objects into a Map, perform grouping, filtering, aggregation, and deduplication operations.

Define the Apple class

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;
    }
}

Create test data

List<Apple> appleList = new ArrayList<>();
Apple apple1 = new Apple(1, "苹果1", new BigDecimal("3.25"), 10);
Apple apple12 = new Apple(1, "苹果2", new BigDecimal("1.35"), 20);
Apple apple2 = new Apple(2, "香蕉", new BigDecimal("2.89"), 30);
Apple apple3 = new Apple(3, "荔枝", new BigDecimal("9.99"), 40);
appleList.add(apple1);
appleList.add(apple12);
appleList.add(apple2);
appleList.add(apple3);

1. Grouping by id

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

2. Convert List to Map (id as key, Apple as value)

Map<Integer, Apple> appleMap = appleList.stream()
    .collect(Collectors.toMap(Apple::getId, a -> a, (k1, k2) -> k1));
System.err.println("appleMap:" + appleMap);

3. Filter elements (e.g., name equals "香蕉")

List<Apple> filterList = appleList.stream()
    .filter(a -> a.getName().equals("香蕉"))
    .collect(Collectors.toList());
System.err.println("filterList:" + filterList);

4. Sum a numeric field (total money)

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

5. Find maximum and minimum values (example with Dish )

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);

6. Remove duplicates based on id

List<Apple> unique = appleList.stream()
    .collect(Collectors.collectingAndThen(
        Collectors.toCollection(() -> new TreeSet<>(Comparator.comparingLong(Apple::getId))),
        ArrayList::new));

The article also includes a table of static factory methods of Collectors, an illustrative image, and a link to the original source containing additional interview questions.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

deduplicationStreamsfilteringaggregationgroupingList to Map
Architect's Tech Stack
Written by

Architect's Tech Stack

Java backend, microservices, distributed systems, containerized programming, and more.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.