Partner – Microsoft – NPI EA (cat = Baeldung)
announcement - icon

Azure Container Apps is a fully managed serverless container service that enables you to build and deploy modern, cloud-native Java applications and microservices at scale. It offers a simplified developer experience while providing the flexibility and portability of containers.

Of course, Azure Container Apps has really solid support for our ecosystem, from a number of build options, managed Java components, native metrics, dynamic logger, and quite a bit more.

To learn more about Java features on Azure Container Apps, visit the documentation page.

You can also ask questions and leave feedback on the Azure Container Apps GitHub page.

Partner – Microsoft – NPI EA (cat= Spring Boot)
announcement - icon

Azure Container Apps is a fully managed serverless container service that enables you to build and deploy modern, cloud-native Java applications and microservices at scale. It offers a simplified developer experience while providing the flexibility and portability of containers.

Of course, Azure Container Apps has really solid support for our ecosystem, from a number of build options, managed Java components, native metrics, dynamic logger, and quite a bit more.

To learn more about Java features on Azure Container Apps, you can get started over on the documentation page.

And, you can also ask questions and leave feedback on the Azure Container Apps GitHub page.

Partner – Orkes – NPI EA (cat=Spring)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

Partner – Orkes – NPI EA (tag=Microservices)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – MongoDB – NPI EA (tag=MongoDB)
announcement - icon

Traditional keyword-based search methods rely on exact word matches, often leading to irrelevant results depending on the user's phrasing.

By comparison, using a vector store allows us to represent the data as vector embeddings, based on meaningful relationships. We can then compare the meaning of the user’s query to the stored content, and retrieve more relevant, context-aware results.

Explore how to build an intelligent chatbot using MongoDB Atlas, Langchain4j and Spring Boot:

>> Building an AI Chatbot in Java With Langchain4j and MongoDB Atlas

Partner – LambdaTest – NPI EA (cat=Testing)
announcement - icon

Accessibility testing is a crucial aspect to ensure that your application is usable for everyone and meets accessibility standards that are required in many countries.

By automating these tests, teams can quickly detect issues related to screen reader compatibility, keyboard navigation, color contrast, and other aspects that could pose a barrier to using the software effectively for people with disabilities.

Learn how to automate accessibility testing with Selenium and the LambdaTest cloud-based testing platform that lets developers and testers perform accessibility automation on over 3000+ real environments:

Automated Accessibility Testing With Selenium

eBook – Java Streams – NPI (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Reactive – NPI(cat= Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

1. Introduction

In this tutorial, we’ll compare Java Stream and Flux.fromIterable(). We’ll start by exploring their similarities and then dive into their key differences.

2. Java Stream Overview

A Stream represents a sequence of elements supporting functional-style operations. Stream instances are synchronous, pull-based, and process elements only when a terminal operation is invoked.

Let’s look at its key characteristics:

  • Supports sequential and parallel execution
  • Uses functional-style operations (map(), filter(), etc.)
  • Lazy execution (executes when the terminal operation is applied)
  • Synchronous and pull-based

3. Flux.fromIterable() Overview

Flux.fromIterable() is a factory method in Project Reactor that creates a Flux from an existing Iterable such as a List, Set, or Collection. It’s useful when we have a collection of data and want to process it reactively.

Here are its key characteristics:

  • Supports asynchronous and non-blocking processing
  • Provides reactive programming operations (map(), filter(), flatMap(), etc.)
  • Push-based – data is emitted as it becomes available

4. Similarities Between Stream and Flux.fromIterable()

Despite being built for different paradigms, both Stream and Flux.fromIterable() share some commonalities. Let’s take a closer look at these commonalities and understand how they align in data processing.

4.1. Functional Style

Both of these support the functional style of programming. We can use filter(), map(), and reduce()-like operations and also chain multiple operations together to create a declarative and readable pipeline for processing data.

Let’s look into an example where we filter a list of numbers to retain only the even ones and then double their values:

@Test
void givenList_whenProcessedWithStream_thenReturnDoubledEvenNumbers() {
    List<Integer> numbers = List.of(1, 2, 3, 4, 5);

    List<Integer> doubledEvenNumbers = numbers.stream()
      .filter(n -> n % 2 == 0)
      .map(n -> n * n)
      .toList();
    assertEquals(List.of(4, 16), doubledEvenNumbers);
}

Now, let’s execute the same example using Flux.fromIterable():

@Test
void givenList_whenProcessedWithFlux_thenReturnDoubledEvenNumbers() {
    List<Integer> numbers = List.of(1, 2, 3, 4, 5);
    Flux<Integer> fluxPipeline = Flux.fromIterable(numbers)
      .filter(n -> n % 2 == 0)
      .map(n -> n * 2);

    StepVerifier.create(fluxPipeline)
      .expectNext(4, 16);
}

4.2. Lazy Evaluation

Both Stream and Flux instances are lazy, meaning operations are only performed when the result is actually needed.

For Stream instances, a terminal operator is needed to execute the pipeline:

@Test
void givenList_whenNoTerminalOperator_thenNoResponse() {
    List<Integer> numbers = List.of(1, 2, 3, 4, 5);
    Function<Integer, Integer> mockMapper = mock(Function.class);
    Stream<Integer> streamPipeline = numbers.stream()
      .map(mockMapper);
    verifyNoInteractions(mockMapper);

    List<Integer> mappedList = streamPipeline.toList();
    verify(mockMapper, times(5));
}

In this example we can see, that there is no interaction with the mockMapper function until the terminal operator toList() is called.

Similarly, the Flux only starts processing when there is a subscriber:

@Test
void givenList_whenFluxNotSubscribed_thenNoResponse() {
    Function<Integer, Integer> mockMapper = mock(Function.class);
    when(mockMapper.apply(anyInt())).thenAnswer(i -> i.getArgument(0));
    List<Integer> numbers = List.of(1, 2, 3, 4, 5);
    Flux<Integer> flux = Flux.fromIterable(numbers)
      .map(mockMapper);

    verifyNoInteractions(mockMapper);

    StepVerifier.create(flux)
      .expectNextCount(5)
      .verifyComplete();

    verify(mockMapper, times(5)).apply(anyInt());
}

In this example, we can verify that Flux doesn’t interact with mockMapper initially. However, once we subscribe to it using StepVerifier, we can observe that Flux starts interacting with its method.

5. Key Differences Between Stream and Flux.fromIterable()

Although there are a few similarities between Stream and Flux.fromIterable(), they differ in their purpose, nature, and how they process elements. Let’s explore some key differences between these two.

5.1. Synchronous vs. Asynchronous

One of the key differences between Stream and Flux.fromIterable() is how they handle execution.

Stream operates synchronously, meaning computations happen sequentially on the same thread invoking the terminal operation. If we process a large dataset or perform time-consuming tasks with a Stream, it can block the thread until completion. There is no built-in way to execute a Stream instance asynchronously without explicitly using parallelStream() or manually managing threads. Even in parallel mode, streams run in a blocking manner.

On the other hand, Flux.fromIterable() focuses on synchronous vs. asynchronous. By default, it behaves synchronously – emitting elements on the calling thread, similar to a sequential stream. However, Flux provides built-in support for asynchronous and non-blocking execution, which can be enabled using operators like subscribeOn(), publishOn(), and delayElements(). This allows Flux to process elements concurrently without blocking the main thread, making it more suitable for reactive applications.

Let’s examine the asynchronous behavior of Flux.fromIterable():

@Test
void givenList_whenProcessingTakesLongerThanEmission_thenEmittedBeforeProcessing() {
    VirtualTimeScheduler.set(VirtualTimeScheduler.create());

    List<Integer> numbers = List.of(1, 2, 3, 4, 5);
    Flux<Integer> sourceFlux = Flux.fromIterable(numbers)
      .delayElements(Duration.ofMillis(500));

    Flux<Integer> processedFlux = sourceFlux.flatMap(n ->
      Flux.just(n * n)
        .delayElements(Duration.ofSeconds(1))
    );

    StepVerifier.withVirtualTime(() -> Flux.merge(sourceFlux, processedFlux))
      .expectSubscription()
      .expectNoEvent(Duration.ofMillis(500))
      .thenAwait(Duration.ofMillis(500 * 5))
      .expectNextCount(7)
      .thenAwait(Duration.ofMillis(5000))
      .expectNextCount(3)
      .verifyComplete();
}

In the above example, we emit numbers every 500ms and delay the processing by 1s. Using merge(), we merge the results of both Flux instances. At the end of 2500ms, all elements are emitted and two have been processed, hence we expect seven items in total. After five seconds, all the elements are processed, so we expect the remaining three items.

Here, the emitter doesn’t wait for the processor to finish its operation, rather it keeps emitting the values independently.

5.2. Exception Handling

In Stream, exception causes immediate termination of the pipeline. If an element throws an exception during processing, the entire stream stops and no further elements are processed.

This is because Stream instances treat exceptions as terminal events. We must rely on try-catch blocks inside the map(), filter(), or use custom exception handling logic at each stage to prevent failure from propagating.

Let’s take a look at how a Stream pipeline behaves when encountering a division by zero exception:

@Test
void givenList_whenDividedByZeroInStream_thenThrowException() {
    List<Integer> numbers = List.of(1, 2, 0, 4, 5);
    assertThrows(ArithmeticException.class, () -> numbers.stream()
      .map(n -> 10 / n)
      .toList());
}

Here, the exception terminates the pipeline immediately, and 4, and 5 are never processed.

In contrast, Flux treats errors as data, meaning errors are propagated through a separate error channel rather than terminating the pipeline outright. This allows us to handle exceptions gracefully by using built-in methods like onErrorResume(), onErrorContinue(), and onErrorReturn(), available in Flux, ensuring the processing can continue even when individual elements fail.

Now, let’s see how the same processing works with Flux.fromIterable():

@Test
void givenList_whenDividedByZeroInFlux_thenReturnFallbackValue() {
    List<Integer> numbers = List.of(1, 2, 0, 4, 5);
    Flux<Integer> flux = Flux.fromIterable(numbers)
      .map(n -> 10 / n)
      .onErrorResume(e -> Flux.just(-1));

    StepVerifier.create(flux)
      .expectNext(10, 5, -1)
      .verifyComplete();
}

Here the exception is caught, and instead of failing, Flux emits a fallback value (-1). This makes Flux more resilient, allowing it to handle real-world scenarios like network failure, database error, or unexpected input.

5.3. Single Pipeline vs. Multiple Subscribers

A fundamental limitation of Stream is that it represents a single-use pipeline. Once a terminal operation, like forEach() or collect() is invoked, the Stream is consumed and cannot be reused. Each time we need to process the same dataset, a new Stream must be created:

@Test
void givenStream_whenReused_thenThrowException() {
    List<Integer> numbers = List.of(1, 2, 3, 4, 5);
    Stream<Integer> doubleStream = numbers.stream()
      .map(n -> n * 2);

    assertEquals(List.of(2, 4, 6, 8, 10), doubleStream.toList());

    assertThrows(IllegalStateException.class, doubleStream::toList);
}

In the above example, when we call the terminal operation toList() on the Stream for the first time, it returns the expected result. However, when we attempt to invoke it again, it throws an IllegalStateException because Stream instances cannot be reused once they have been consumed.

On the other hand, Flux supports multiple subscribers, allowing different consumers to react to the same data independently. This enables event-driven architectures where multiple components in a system can respond to the same data stream without reloading the source.

Now, let’s perform the same operation using Flux and see how it behaves:

@Test
void givenFlux_whenMultipleSubscribers_thenEachReceivesData() {
    List<Integer> numbers = List.of(1, 2, 3, 4, 5);
    Flux<Integer> flux = Flux.fromIterable(numbers).map(n -> n * 2);
    StepVerifier.create(flux)
      .expectNext(2, 4, 6, 8, 10)
      .verifyComplete();

    StepVerifier.create(flux)
      .expectNext(2, 4, 6, 8, 10)
      .verifyComplete();
}

Here, we can see that each subscriber has received the same data and there is no exception thrown. This makes Flux more versatile than Stream, especially in scenarios where multiple components need to listen to and process the same data without duplicating the source.

5.4. Performance

Stream instances are optimized for high-performance in-memory processing. They operate eagerly, meaning all transformations happen in a single pass over the data.

Additionally, Stream supports parallel processing using parallelStream(), utilizing multiple CPU cores via ForkJoinPool to further improve execution speed for large datasets.

On the other hand, Flux.fromIterable() is designed for reactive data handling, making it more flexible but inherently slower for in-memory computations.

Since Flux is asynchronous by nature, every data element is wrapped in reactive signals (onNext, onError, onComplete), adding processing overhead.

Flux follows a non-blocking execution model, which can be beneficial for I/O heavy operations but less efficient for purely computational tasks.

6. Feature Comparison: Java Stream vs. Flux.fromIterable()

Feature Java Stream Flux.fromIterable()
Execution Model Pull-based – The consumer requests data when needed Push-based – The producer pushes data to the consumer asynchronously
Processing Style Functional, pipeline-base Functional, reactive, event-based
Synchronous or Asynchronous Synchronous – Can be parallelized using parallelStream() Asynchronous – Can execute on multiple threads without blocking
Error Handling No built-in support. We need to use a try-catch block Errors are treated as data and propagated through a separate error channel
Multiple Subscribers Not supported – Once consumed, the stream cannot be reused Multiple subscribers can listen to the same Flux
Use case Useful for fast, CPU-bound, in-memory transformations When we need reactive features like asynchronous and non-blocking, handle errors reactively, and batch processing

7. Conclusion

In this article, we explored the similarities and key differences between Java’s Stream and Reactor’s Flux.fromIterable(). Understanding these distinctions allows us to choose the right approach based on our application’s needs.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

Partner – Microsoft – NPI EA (cat = Baeldung)
announcement - icon

Azure Container Apps is a fully managed serverless container service that enables you to build and deploy modern, cloud-native Java applications and microservices at scale. It offers a simplified developer experience while providing the flexibility and portability of containers.

Of course, Azure Container Apps has really solid support for our ecosystem, from a number of build options, managed Java components, native metrics, dynamic logger, and quite a bit more.

To learn more about Java features on Azure Container Apps, visit the documentation page.

You can also ask questions and leave feedback on the Azure Container Apps GitHub page.

Partner – Microsoft – NPI EA (cat = Spring Boot)
announcement - icon

Azure Container Apps is a fully managed serverless container service that enables you to build and deploy modern, cloud-native Java applications and microservices at scale. It offers a simplified developer experience while providing the flexibility and portability of containers.

Of course, Azure Container Apps has really solid support for our ecosystem, from a number of build options, managed Java components, native metrics, dynamic logger, and quite a bit more.

To learn more about Java features on Azure Container Apps, visit the documentation page.

You can also ask questions and leave feedback on the Azure Container Apps GitHub page.

Partner – Orkes – NPI EA (cat = Spring)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

Partner – Orkes – NPI EA (tag = Microservices)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Partner – MongoDB – NPI EA (tag=MongoDB)
announcement - icon

Traditional keyword-based search methods rely on exact word matches, often leading to irrelevant results depending on the user's phrasing.

By comparison, using a vector store allows us to represent the data as vector embeddings, based on meaningful relationships. We can then compare the meaning of the user’s query to the stored content, and retrieve more relevant, context-aware results.

Explore how to build an intelligent chatbot using MongoDB Atlas, Langchain4j and Spring Boot:

>> Building an AI Chatbot in Java With Langchain4j and MongoDB Atlas

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

eBook – Java Streams – NPI (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook Jackson – NPI EA – 3 (cat = Jackson)