Introduction
With Java 8, Oracle introduced several groundbreaking features, but one of the most powerful and impactful is the Stream API. It enables functional-style programming for processing sequences of elements, such as collections, arrays, or I/O channels.
Objective
The aim of this article is to provide a deep understanding of the Java 8 Stream API, including what it is, how it differs from traditional loops, and how to use its powerful features such as map, filter, reduce, collect, and more.
What is a Stream?
A Stream is not a data structure. It represents a sequence of elements supporting sequential and parallel aggregate operations. Unlike collections, Streams do not store elements. Instead, they convey elements from a source (like a list or set) through a pipeline of computational operations.
Stream vs Collection
- Collection: Stores and retrieves data.
- Stream: Describes computations on data.
- Streams can be consumed only once.
How to Create Streams
import java.util.*;
import java.util.stream.*;
public class StreamExample {
public static void main(String[] args) {
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
Stream<String> stream = names.stream(); // Creates a sequential stream
Stream<String> parallelStream = names.parallelStream(); // Creates a parallel stream
}
}
Stream Operations
Stream operations are either intermediate or terminal.
- Intermediate: map, filter, sorted (returns another stream)
- Terminal: collect, forEach, reduce (produces a result or side-effect)
Common Stream Methods with Examples
1. forEach()
List<String> list = Arrays.asList("Java", "Python", "C++");
list.stream().forEach(System.out::println);
2. filter()
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
numbers.stream()
.filter(n -> n % 2 == 0)
.forEach(System.out::println);
3. map()
List<String> names = Arrays.asList("john", "jane", "doe");
names.stream()
.map(String::toUpperCase)
.forEach(System.out::println);
4. sorted()
List<String> fruits = Arrays.asList("Banana", "Apple", "Mango");
fruits.stream()
.sorted()
.forEach(System.out::println);
5. collect()
List<String> names = Arrays.asList("John", "Jane", "Jack");
List<String> upper = names.stream()
.map(String::toUpperCase)
.collect(Collectors.toList());
System.out.println(upper);
6. reduce()
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
int sum = numbers.stream()
.reduce(0, (a, b) -> a + b);
System.out.println("Sum = " + sum);
Creating Streams from Different Sources
From Arrays:
int[] nums = {1, 2, 3, 4};
IntStream stream = Arrays.stream(nums);
From String:
"Hello World".chars().forEach(ch -> System.out.println((char) ch));
Stream Pipeline
A typical stream pipeline looks like this:
source -> intermediate operations -> terminal operation
Example: Filter and Collect
List<String> list = Arrays.asList("cat", "dog", "elephant");
List<String> filtered = list.stream()
.filter(s -> s.length() > 3)
.collect(Collectors.toList());
System.out.println(filtered);
Parallel Streams
List<Integer> numbers = Arrays.asList(1,2,3,4,5,6,7,8,9);
int sum = numbers.parallelStream()
.reduce(0, Integer::sum);
System.out.println("Parallel Sum = " + sum);
Stream with Custom Objects
class Employee {
String name;
int salary;
Employee(String name, int salary) {
this.name = name;
this.salary = salary;
}
}
public class Test {
public static void main(String[] args) {
List<Employee> employees = Arrays.asList(
new Employee("John", 5000),
new Employee("Jane", 7000),
new Employee("Jack", 4000)
);
employees.stream()
.filter(e -> e.salary > 4500)
.map(e -> e.name)
.forEach(System.out::println);
}
}
Advanced: Grouping and Partitioning
Map<Integer, List<String>> groupedByLength =
Stream.of("Java", "Python", "JS", "C")
.collect(Collectors.groupingBy(String::length));
System.out.println(groupedByLength);
Best Practices
- Use streams for bulk operations on collections.
- Avoid side-effects in lambda expressions.
- Use parallel streams only when processing is CPU intensive.
- Always remember that streams are lazy and evaluated only when terminal operation is called.
When Not to Use Streams
- When you need indexed access (e.g., with arrays).
- For simple loops — stream syntax may be overkill.
- When performance tuning is critical and streams introduce overhead.
Conclusion
The Stream API in Java 8 revolutionizes how we interact with data structures in Java. By allowing you to write more declarative and functional code, it improves readability and reduces boilerplate. Through this tutorial, you’ve learned the core functionality of streams and how to apply it with real examples.
Hello There. I found your blog using msn. This is a very well written article. I will make sure to bookmark it and come back to read more of your useful information. Thanks for the post. I will definitely return.
Your article helped me a lot, is there any more related content? Thanks! https://accounts.binance.bh/en-IN/register-person?ref=WTOZ531Y
Понял, что стены мешают — и тут началась бюрократия. Знакомые говорили, что это долго и дорого. Сделали проект, подготовили документы. согласование перепланировки в Москве — они сделали всё под ключ. Квартира станет удобнее и просторнее. Не мучайтесь сами — доверьтесь профессионалам. ресог ресог Сохраните, поделитесь, не потеряйте для нашего города. Они знают все нюансы и проведут вас через все этапы. Сделайте ремонт правильно — без нервов и штрафов!
Когда я увидел, как мой брат лежит на диване, не двигаясь. А он не хотел, он просто лежал и молчал. Позвонил, объяснил ситуацию, и мне сказали: «Приедем через час». Вывод из запоя на дому — это было единственное, что помогло. Поставил капельницу, ввёл нужные препараты. Мы расплатились, и врач уехал. выведение из запоя в щелково выведение из запоя в щелково Там все контакты и цены для нашего города. Если ваш близкий в запое — не ждите. Вывод из запоя на дому — это реальность, и она работает!
Your point of view caught my eye and was very interesting. Thanks. I have a question for you. https://accounts.binance.bh/en/register?ref=SMUBFN5I
I’ve been looking for a reliable spot to play and this one really delivers. The interface is smooth and the payouts are fast. Definitely checking out br76fbet again tonight!
Been spinning here for a few months and the variety of games keeps me coming back. The live dealer section feels like being in a real casino. Staff is polite and the promotions are actually useful. bdw999
Heya are using WordPress for your blog platform? I’m new to the blog world but I’m trying to get started and create my own. Do you need any html coding expertise to make your own blog? Any help would be really appreciated!
Hi there! Someone in my Facebook group shared this site with us so I came to check it out. I’m definitely loving the information. I’m bookmarking and will be tweeting this to my followers! Terrific blog and outstanding design.
I love how I can place my bets on the go. The app is stable and the odds are very competitive compared to others. 77888betapp is a winner.
Illinois sex guideFree strap on wife sexWinnipeg amateur pornAnme hentaiJapanese pussy with
q tipsRevenge picture nudeWeening off of breast milk xnxx Pregnangt fetishCuthbert
elisha pigtails xxxFacial servicesMature show me your titsBottom up saliency is a discriminant processMother and nudeBreast cancer awareness
door decorating contestWhere to buy adult dvds inAdult banner
design blog.jumpandread.com Develope breastFree amateur mature wife videosFlicklife ebony bbw bootylicous babe septemberSuck grandmas saggy titsTransvestites devon ukExpiration for condomsAsian ladyboys tubesBusty samantha at big naturalLingerie zwangerschap corset xnxx Watch naked girlsVintage reportAss in pansBell bottoms in hurst texasHot teens in pornHot lesbians fishnetsBreast enlargement atlanta gaGay
young pixIncreasing penis size with steroidsFemale sex
with dogs pay sitesClebrities breastSmal boy fuck woman movieSexy
cheerleading costumDouble monster cocks
А ты не знаешь, куда обратиться. Боятся оставить одного. Вызов нарколога на дом — это когда врач приезжает сам. Сначала уходит интоксикация. Анонимная наркологическая помощь — И в выходные. Можете ознакомиться по ссылке: наркологическая служба на дом https://pomoshch.narkolog-na-dom-msk-qdw.ru Там и про телефон нарколога на дом для Москвы. Иногда один звонок решает всё.
Finally found a place where the bonuses actually make sense. Had a great run yesterday and the withdrawal was super quick. phluckyplayph is the way to go!
The gameplay here is just top notch. I had a few questions and the support team handled them quickly. Big thumbs up for br3333br for the great service!
Hiya, I am really glad I have found this info. Nowadays bloggers publish only about gossips and web and this is really irritating. A good site with exciting content, this is what I need. Thanks for keeping this web site, I’ll be visiting it. Do you do newsletters? Cant find it.