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.
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
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
> 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
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
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.485. Find maximum and minimum values (example with Dish )
Optional
maxDish = Dish.menu.stream()
.collect(Collectors.maxBy(Comparator.comparing(Dish::getCalories)));
maxDish.ifPresent(System.out::println);
Optional
minDish = Dish.menu.stream()
.collect(Collectors.minBy(Comparator.comparing(Dish::getCalories)));
minDish.ifPresent(System.out::println);6. Remove duplicates based on id
List
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.
Architect's Tech Stack
Java backend, microservices, distributed systems, containerized programming, and more.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.