Unlock Java 8 Streams: Simplify Collections with Powerful Operations
This article introduces Java 8 Stream API, explains how to create streams from collections, demonstrates common intermediate operations such as filter, map, flatMap, limit, skip, distinct, sorted, peek, and shows terminal actions like forEach, count, max, min, findFirst, findAny, and match methods with practical code examples.
In everyday development, iterating over arrays or collections with traditional for‑loops can be verbose; Java 8 introduced the Stream API to make such operations concise and elegant.
A sequence of elements supporting sequential and parallel aggregate operations.
This definition means a Stream processes a data source (e.g., a list or array) through a pipeline of operations, similar to a factory assembly line, and finally produces a result.
1. What Is a Stream?
A Stream is a pipeline that consists of three parts: creation, intermediate processing, and result retrieval.
2. Creating Streams
2.1 stream()
Creates a sequential stream from a collection.
List<Person> list = new ArrayList<>();
list.add(new Person("玄武1", 32, 1, "四川绵阳"));
list.add(new Person("玄武2", 33, 2, "四川成都"));
list.add(new Person("玄武3", 12, 1, "四川成都"));
list.add(new Person("玄武4", 23, 2, "四川德阳"));
Stream<Person> stream = list.stream();2.2 parallelStream()
Creates a parallel stream.
Stream<Person> personStream = list.parallelStream();2.3 Stream.of()
Creates a stream from given elements.
public static <T> Stream<T> of(T... values) {
return Arrays.stream(values);
}
Stream<Integer> integerStream = Stream.of(1, 2, 3, 4, 5, 6, 7);3. Intermediate Operations
3.1 filter
Filters elements that match a predicate.
stream.filter(s -> "玄武1".equals(s.getName()))
.forEach(System.out::println);Output:
Person(name=玄武1, age=32, sex=1, address=四川绵阳)3.2 map
Transforms each element to another form (one‑to‑one).
stream.map(s -> s.getAddress())
.forEach(System.out::println);Output:
四川绵阳
四川成都
四川成都
四川德阳
湖北武汉
四川阿坝
重庆市
四川德阳
四川成都
四川成都3.3 flatMap
Flattens nested streams (one‑to‑many).
List<Person> list = new ArrayList<>();
// ...add 10 persons as above ...
List<List<Person>> allList = new ArrayList<>();
allList.add(list);
List<Person> list2 = new ArrayList<>();
list2.add(new Person("玄武11", 23, 1, "四川成都"));
allList.add(list2);
System.out.println("------------map---------------");
List<Stream<Person>> collect = allList.stream()
.map(s -> s.stream())
.collect(Collectors.toList());
collect.forEach(System.out::println);
System.out.println("----------flatmap-----------");
List<Person> collect1 = allList.stream()
.flatMap(s -> s.stream())
.collect(Collectors.toList());
collect1.forEach(System.out::println);Output shows that map produces a list of stream objects, while flatMap merges all persons into a single stream.
3.4 limit
Keeps only the first *n* elements.
stream.limit(2)
.forEach(s -> System.out.println("姓名:" + s.getName() + ",地址:" + s.getAddress()));Output:
姓名:玄武1,地址:四川绵阳
姓名:玄武2,地址:四川成都3.5 skip
Skips the first *n* elements.
stream.skip(3).forEach(System.out::println);Output:
Person(name=玄武4, age=23, sex=2, address=四川德阳)
Person(name=玄武5, age=43, sex=2, address=湖北武汉)
Person(name=玄武6, age=12, sex=1, address=四川阿坝)
Person(name=玄武7, age=54, sex=2, address=重庆市)
Person(name=玄武8, age=23, sex=1, address=四川德阳)
Person(name=玄武9, age=32, sex=2, address=四川成都)
Person(name=玄武10, age=33, sex=1, address=四川成都)3.6 distinct
Removes duplicate elements.
list.add(new Person("玄武10", 33, 1, "四川成都")); // duplicate
stream.distinct().forEach(System.out::println);Output shows each person appears only once.
3.7 sorted
Sorts elements according to a comparator.
stream.sorted(Comparator.comparingInt(Person::getAge))
.forEach(System.out::println);Output (by age ascending):
Person(name=玄武3, age=12, sex=1, address=四川成都)
Person(name=玄武6, age=12, sex=1, address=四川阿坝)
Person(name=玄武4, age=23, sex=2, address=四川德阳)
Person(name=玄武8, age=23, sex=1, address=四川德阳)
Person(name=玄武1, age=32, sex=1, address=四川绵阳)
Person(name=玄武9, age=32, sex=2, address=四川成都)
Person(name=玄武2, age=33, sex=2, address=四川成都)
Person(name=玄武10, age=33, sex=1, address=四川成都)
Person(name=玄武5, age=43, sex=2, address=湖北武汉)
Person(name=玄武7, age=54, sex=2, address=重庆市)3.8 peek
Allows inspection of each element during processing, mainly for debugging.
stream.peek(System.out::println)
.map(s -> "玄武1".equals(s.getName()))
.forEach(System.out::println);Output shows the original objects followed by boolean results.
4. Terminal Operations
4.1 forEach
stream.forEach(System.out::println);4.2 count, max, min
System.out.println(stream.filter(s -> s.getAge() > 20).count()); // 8
System.out.println(stream.filter(s -> s.getAge() > 20)
.max(Comparator.comparingInt(Person::getAge)).get()); // Person with age 54
System.out.println(stream.filter(s -> s.getAge() > 20)
.min(Comparator.comparingInt(Person::getAge)).get()); // Person with age 234.3 findFirst & findAny
Person p1 = list.stream().findFirst().get();
System.out.println(p1);
Person p2 = list.stream().findAny().get();
System.out.println(p2);4.4 Matching Operations
boolean any = list.stream().anyMatch(s -> "玄武7".equals(s.getName()));
System.out.println(any); // true
boolean all = list.stream().allMatch(s -> "玄武7".equals(s.getName()));
System.out.println(all); // false
boolean none = list.stream().noneMatch(s -> "玄武7".equals(s.getName()));
System.out.println(none); // falseThe article concludes that Stream API provides a rich set of operations for functional-style processing of collections, making code more readable and expressive.
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.
Xuanwu Backend Tech Stack
Primarily covers fundamental Java concepts, mainstream frameworks, deep dives into underlying principles, and JVM internals.
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.
