Java 8 Stream API: Grouping, Mapping, Filtering, Summing and Other Collection Operations
This article demonstrates how to leverage Java 8 Stream API to perform common collection operations such as defining a data class, creating test data, grouping by fields, converting lists to maps, filtering, summing numeric fields, finding max/min values, removing duplicates, and explains the Collectors utility methods.
Utilizing Java 8 new features, you can write concise and efficient code for various data processing tasks.
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 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
Group objects in the list by a specific attribute (e.g., id) using Collectors.groupingBy:
Map<Integer, List<Apple>> groupBy = appleList.stream()
.collect(Collectors.groupingBy(Apple::getId));
System.err.println("groupBy:" + groupBy);2. List to Map
Convert the list to a map where id is the key and the Apple object is the value. Handle duplicate keys with a merge function:
Map<Integer, Apple> appleMap = appleList.stream()
.collect(Collectors.toMap(Apple::getId, a -> a, (k1, k2) -> k1));
System.err.println(appleMap);3. Filtering
Filter elements that meet a condition, such as name equals "香蕉":
List<Apple> filterList = appleList.stream()
.filter(a -> a.getName().equals("香蕉"))
.collect(Collectors.toList());
System.err.println("filterList:" + filterList);4. Summing
Calculate the total amount of money across all objects:
BigDecimal totalMoney = appleList.stream()
.map(Apple::getMoney)
.reduce(BigDecimal.ZERO, BigDecimal::add);
System.err.println("totalMoney:" + totalMoney); // totalMoney:17.485. Max/Min
Find the maximum and minimum elements in a stream using Collectors.maxBy and Collectors.minBy (example shown with a Dish class):
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. De‑duplication
Remove duplicates based on id using collectingAndThen with a TreeSet:
import static java.util.Comparator.comparingLong;
import static java.util.stream.Collectors.collectingAndThen;
import static java.util.stream.Collectors.toCollection;
List<Apple> unique = appleList.stream()
.collect(collectingAndThen(
toCollection(() -> new TreeSet<>(comparingLong(Apple::getId))),
ArrayList::new));The table below lists the static factory methods of the Collectors class and their purposes:
Factory Method
Return Type
Function
toList List<T> Collects all stream elements into a List
toSet Set<T> Collects all stream elements into a Set, removing duplicates
toCollection Collection<T> Collects into a collection created by a supplied factory
counting
Long
Counts the number of elements in the stream
sumInt
Integer
Sums an integer property of the stream elements
averagingInt
Double
Computes the average of an integer property
summarizingInt
IntSummaryStatistics
Provides statistics (max, min, sum, average) for an integer property
joining
String
Concatenates the string representations of stream elements
maxBy Optional<T> Returns an Optional containing the maximum element according to a comparator
minBy Optional<T> Returns an Optional containing the minimum element according to a comparator
reducing
Result type of reduction
Reduces the stream to a single value using an initial value and a binary operator
collectingAndThen
Result type after applying a finishing function
Wraps another collector and applies a finishing transformation
groupingBy Map<K, List<T>> Groups stream elements by a classifier function
partitioningBy Map<Boolean, List<T>> Partitions stream elements based on a predicate
END
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Java Captain
Focused on Java technologies: SSM, the Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading; occasionally covers DevOps tools like Jenkins, Nexus, Docker, ELK; shares practical tech insights and is dedicated to full‑stack Java development.
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.
