Master Java Stream API: 15 Real-World Examples and Performance Tips
Explore 15 practical Java Stream API examples—from filtering and mapping to parallel processing and JPA integration—demonstrating how to write concise, efficient code, improve performance, and avoid memory issues, with full code snippets and explanations for each use case.
Spring Boot 3 practical case collection (124 cases) includes a dedicated section on Java Stream API, showcasing how to use streams for concise and maintainable data processing.
1. Introduction
Java Stream, introduced in Java 8, provides a declarative way to process collections (lists, sets, etc.). It supports intermediate operations (filter, map, sorted) that return a stream for chaining, and terminal operations (collect, forEach, reduce) that produce a result or side‑effect. Streams can run in parallel, leveraging multi‑core CPUs while keeping user code unchanged.
2. Practical Examples
2.1 Find all even numbers and sum
public static void p1(){
List<Integer> numbers = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
int sum = numbers.stream()
.filter(num -> num % 2 == 0)
.mapToInt(Integer::intValue)
.sum();
System.err.printf("result: %s%n", sum);
}2.2 Count strings longer than 5 characters
public static void p2(){
List<String> strings = Arrays.asList("apple","banana","grape","watermelon","kiwi","orange");
Long count = strings.stream()
.filter(str -> str.length() > 5)
.count();
System.err.printf("result: %s%n", count);
}2.3 Transform each element and collect to a new list
public static void p3(){
List<Integer> numbers = Arrays.asList(1,2,3,4,5);
List<Integer> squares = numbers.stream()
.map(num -> num * num)
.collect(Collectors.toList());
System.err.printf("result: %s%n", squares);
}2.4 Find the maximum element in an integer list
public static void p4(){
List<Integer> numbers = Arrays.asList(10,5,25,15,30);
int max = numbers.stream()
.mapToInt(Integer::intValue)
.max()
.getAsInt();
System.err.printf("result: %s%n", max);
}2.5 Concatenate all strings in a list
public static void p5(){
List<String> fruits = Arrays.asList("apple","banana","cherry","coconut","apple");
String concat = fruits.stream()
.collect(Collectors.joining());
System.err.printf("result: %s%n", concat);
}2.6 Convert to uppercase and sort
public static void p6(){
List<String> fruits = Arrays.asList("apple","Banana","Grape","orange","kiwi");
List<String> sortedUppercase = fruits.stream()
.map(String::toUpperCase)
.sorted()
.collect(Collectors.toList());
System.err.printf("result: %s%n", sortedUppercase);
}2.7 Compute average of double values
public static void p7(){
List<Double> doubles = Arrays.asList(1.0,2.0,3.0,4.0,5.0);
double average = doubles.stream()
.mapToDouble(Double::doubleValue)
.average()
.getAsDouble();
System.err.printf("result: %s%n", average);
}2.8 Remove duplicate elements
public static void p8(){
List<String> words = Arrays.asList("apple","banana","apple","orange","banana","kiwi");
List<String> uniqueWords = words.stream()
.distinct()
.collect(Collectors.toList());
System.err.printf("result: %s%n", uniqueWords);
}2.9 Check if all elements satisfy a condition
public static void p9(){
List<Integer> numbers = Arrays.asList(2,4,6,8,10);
boolean allEven = numbers.stream()
.allMatch(n -> n % 2 == 0);
System.err.printf("result: %s%n", allEven);
}2.10 Check if a collection contains a specific element
public static void p10(){
List<Integer> numbers = Arrays.asList(2,4,6,8,10);
boolean exists = numbers.stream()
.anyMatch(n -> n.equals(8));
System.err.printf("result: %s%n", exists);
}2.11 Find the longest string length
public static void p11(){
List<String> fruits = Arrays.asList("apple","banana","cherry","coconut","apple");
int max = fruits.stream()
.mapToInt(String::length)
.max()
.getAsInt();
System.err.printf("result: %s%n", max);
}2.12 Remove null values from a stream
public static void p12(){
List<String> fruits = Arrays.asList("apple","banana","cherry",null,"coconut","apple");
List<String> nonNullValues = fruits.stream()
.filter(Objects::nonNull)
.collect(Collectors.toList());
System.err.printf("result: %s%n", nonNullValues);
}2.13 Group by department and find max salary
public static void p13(){
List<Employee> employees = new ArrayList<>();
employees.add(new Employee("Alice","HR",50000.0));
employees.add(new Employee("Bob","IT",60000.0));
employees.add(new Employee("Charlie","Finance",55000.0));
employees.add(new Employee("David","IT",70000.0));
employees.add(new Employee("Eva","HR",45000.0));
employees.add(new Employee("Frank","Finance",58000.0));
Map<String, Optional<Employee>> highestSalaryPerDept = employees.stream()
.collect(Collectors.groupingBy(Employee::getDepartment,
Collectors.maxBy(Comparator.comparingDouble(Employee::getSalary))));
highestSalaryPerDept.forEach((key, value) -> {
System.err.printf("部门: %s, \t最高薪: %s%n", key, value.get());
});
}2.14 Find the second smallest element
public static void p14(){
List<Integer> numbers = Arrays.asList(2,4,6,8,10);
Optional<Integer> secondSmallest = numbers.stream()
.distinct()
.sorted()
.skip(1)
.findFirst();
System.err.printf("result: %s%n", secondSmallest);
}2.15 Compute intersection of two lists
public static void p15(){
List<Integer> list1 = Arrays.asList(1,2,3,4,5);
List<Integer> list2 = Arrays.asList(4,5,6,7,8);
List<Integer> intersection = list1.stream()
.filter(list2::contains)
.collect(Collectors.toList());
System.err.printf("result: %s%n", intersection);
}2.16 Parallel processing performance demo
public static void main(String[] args) {
double[] arr = IntStream.range(0, 100_000_000)
.mapToDouble(i -> new Random().nextDouble() * 100000)
.toArray();
computeSumOfSquareRoots(arr);
}
public static void computeSumOfSquareRoots(double[] arr) {
double serialSum = computeSerialSum(DoubleStream.of(arr));
System.out.println("Serial Sum: " + serialSum);
double parallelSum = computeParallelSum(DoubleStream.of(arr));
System.out.println("Parallel Sum: " + parallelSum);
}
public static double computeSerialSum(DoubleStream stream) {
long startTime = System.currentTimeMillis();
double sum = stream.reduce(0.0, (l, r) -> l + r);
long endTime = System.currentTimeMillis();
System.out.println("Serial Computation Time: " + (endTime - startTime) + " ms");
return sum;
}
public static double computeParallelSum(DoubleStream stream) {
long startTime = System.currentTimeMillis();
double sum = stream.parallel().reduce(0, (l, r) -> l + r);
long endTime = System.currentTimeMillis();
System.out.println("Parallel Computation Time: " + (endTime - startTime) + " ms");
return sum;
}3. Repository Returning Stream
In Spring Data JPA, a repository method can return Stream<User> instead of List<User>. Using a stream prevents OOM when processing massive result sets because the data is fetched lazily in chunks.
Example signatures:
@Query("select u from User u")
List<User> findAllUserList();
@Query("select u from User u")
Stream<User> findAllUserStream();Memory usage comparison (List vs. Stream):
When large data sets need to be queried, using a Stream is recommended to keep memory consumption low.
End of article.
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.
Spring Full-Stack Practical Cases
Full-stack Java development with Vue 2/3 front-end suite; hands-on examples and source code analysis for Spring, Spring Boot 2/3, and Spring Cloud.
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.
