How Java 8 Stream API Can Multiply Your Coding Efficiency
The article introduces Java 8’s Stream API, showing how to create streams from collections, arrays, and static methods, and demonstrates common operations such as filter, map, flatMap, reduce, collect, grouping, sorting, and limiting, with concrete code examples that replace verbose loops and improve readability.
Java 8 extends the collection classes with a Stream API, allowing developers to create a Stream via Collection.stream() or Collection.parallelStream() and process data without explicit loops.
Creating streams
// From a List
List<String> list = Arrays.asList("zhansan", "lisi", "wangwu");
Stream<String> stream = list.stream();
stream.forEach(System.out::println);
// From an array
String[] array = {"zhansan", "lisi", "wangwu"};
Stream<String> stream2 = Arrays.stream(array);
stream2.forEach(System.out::println);
// From static methods
Stream<String> stream3 = Stream.of("1", "2", "3");
stream3.forEach(System.out::println);
Stream<Integer> stream4 = Stream.iterate(0, x -> x + 3).limit(4);
stream4.forEach(System.out::println);Common Stream operations
1. filter and forEach – replace manual iteration:
userList.stream()
.filter(user -> user.getAge() > 40)
.forEach(item -> System.out.println(item.getAge()));
// Multiple conditions
userList.stream()
.filter(user -> user.getAge() > 40 && user.getAge() < 70)
.forEach(item -> System.out.println(item.getAge()));2. findFirst – get the first matching element:
System.out.println("First match: " +
userList.stream()
.filter(user -> user.getAge() < 60)
.findFirst()
.get()
.getName());3. anyMatch – check if any element satisfies a predicate:
System.out.println("Contains age > 80: " +
userList.stream()
.anyMatch(user -> user.getAge() > 80));4. collect – gather results into a new collection:
List<User> over40 = userList.stream()
.filter(user -> user.getAge() > 40)
.collect(Collectors.toList());5. Aggregations – max, min, count:
Comparator<User> comparator = Comparator.comparing(User::getAge);
int maxAge = userList.stream().max(comparator).get().getAge();
long countOver40 = userList.stream().filter(u -> u.getAge() > 40).count();6. map and flatMap – transform elements:
// Add 10 to each age
userList.stream()
.map(user -> user.getAge() + 10)
.forEach(System.out::println);7. reduce – reduce a stream to a single value (sum, product, max):
List<Integer> nums = Arrays.asList(1, 2, 3, 4);
Optional<Integer> sum = nums.stream().reduce((x, y) -> x + y);
Optional<Integer> product = nums.stream().reduce((x, y) -> x * y);
Optional<Integer> max = nums.stream().reduce((x, y) -> x > y ? x : y);8. Collectors for statistics – counting, averaging, summing, summarizing:
long total = userList.stream().collect(Collectors.counting());
double avg = userList.stream().collect(Collectors.averagingInt(User::getAge));
int sumAge = userList.stream().collect(Collectors.summingInt(User::getAge));
IntSummaryStatistics stats = userList.stream()
.collect(Collectors.summarizingInt(User::getAge));9. Grouping and partitioning:
Map<Boolean, List<User>> byAge50 = userList.stream()
.collect(Collectors.partitioningBy(u -> u.getAge() > 50));
Map<Integer, List<User>> byExactAge = userList.stream()
.collect(Collectors.groupingBy(User::getAge));10. Joining – concatenate strings from a stream:
String names = userList.stream()
.map(User::getName)
.collect(Collectors.joining(" and "));11. Sorting:
// Ascending by age
List<Integer> asc = userList.stream()
.sorted(Comparator.comparing(User::getAge))
.map(User::getAge)
.collect(Collectors.toList());
// Descending by age
List<Integer> desc = userList.stream()
.sorted(Comparator.comparing(User::getAge).reversed())
.map(User::getAge)
.collect(Collectors.toList());12. Concatenating streams and removing duplicates:
String[] arr1 = {"1", "2", "3", "4"};
String[] arr2 = {"3", "4", "5", "6"};
Stream<String> s1 = Stream.of(arr1);
Stream<String> s2 = Stream.of(arr2);
List<String> merged = Stream.concat(s1, s2).collect(Collectors.toList());
List<String> distinct = Stream.concat(s1, s2).distinct().collect(Collectors.toList());13. Limiting and skipping elements:
List<Integer> limited = Stream.iterate(1, x -> x + 2)
.limit(5)
.collect(Collectors.toList());
List<Integer> skipped = Stream.iterate(1, x -> x + 2)
.skip(5)
.limit(5)
.collect(Collectors.toList());Through these examples, the article shows how the Stream API can replace verbose loops, make data processing pipelines clearer, and improve coding efficiency.
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.
The Dominant Programmer
Resources and tutorials for programmers' advanced learning journey. Advanced tracks in Java, Python, and C#. Blog: https://blog.csdn.net/badao_liumang_qizhi
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.
