DEV Community

Raghwendra Sonu
Raghwendra Sonu

Posted on

Streams in Java?

In Java, streams are a powerful and flexible abstraction introduced in Java 8 as part of the java.util.stream package. Streams provide a new way to process data in a functional and declarative manner. They enable developers to express complex data processing operations concisely and efficiently.

Common Operations on Streams:
Filtering:

List filteredList = myList.stream()
.filter(s -> s.startsWith("A"))
.collect(Collectors.toList());

Mapping:

List lengths = myList.stream()
.map(String::length)
.collect(Collectors.toList());

Sorting:

List sortedList = myList.stream()
.sorted()
.collect(Collectors.toList());

Reducing:

Optional concatenated = myList.stream()
.reduce((s1, s2) -> s1 + s2);

Collecting:

List collectedList = myList.stream()
.collect(Collectors.toList());

Grouping and Partitioning:

Map> groupedByLength = myList.stream()
.collect(Collectors.groupingBy(String::length));

Example of Chaining Stream Operations:

List result = myList.stream()
.filter(s -> s.length() > 2)
.map(String::toUpperCase)
.sorted()
.collect(Collectors.toList());

In this example, the stream is filtered to include only strings with a length greater than 2, then each string is converted to uppercase (so the map is used to do additional operation on the result returned from filter), the resulting strings are sorted, and finally, the result is collected into a new list.

Streams simplify the processing of collections in Java, providing a concise and expressive way to manipulate data. They are particularly useful when dealing with large datasets or performing complex data transformations.

Top comments (0)