Articles / Toward Functional Paradigm: Fundamental Concepts in Java
Toward Functional Paradigm: Fundamental Concepts in Java
by crejk on 2025-06-20§ Introduction
Functional Programming offers valuable concepts that can enhance our code quality and maintainability. By using immutable data structures and pure functions, we can push side effects out of most of our code, making it more predictable and easier to debug.
We will dig into the basics, covering the following topics:
- Immutability - State management.
- Functions - Functional programming fundament.
- Working with Optional -
mapandflatMapinstead ofisPresent. - Validation - Making errors explicit.
- Working with Optional -
- Functional iceberg - Where to stop in Java.
§ Immutability
The primary concept with which we may already be familiar is immutability. Immutability ensures that data remains consistent and predictable, making it easier to reason about the state of an application.
§ Immutable objects
Immutable objects, once created, cannot be modified. They remain the same throughout their entire life cycle.
// old fashion way
public class Reservation {
private final ReservationId id;
private final ReservationStatus status;
public Reservation(ReservationId id, ReservationStatus status) {
this.id = id;
this.status = status;
}
// getters
// equals & hashCode
}For years, Java has not had a decent built-in way of defining immutable objects, but we live to see records.
// Java 14+
public record Reservation(ReservationId id, ReservationStatus status) {
}References
The following code doesn't allow us any modification,
the only way to "update" the object is to create a new one with changed values.
public record Reservation(ReservationId id, ReservationStatus status) {
Reservation cancel() {
return new Reservation(id, ReservationStatus.CANCELLED);
}
}What are the main benefits of using immutable objects?
- Immutable objects are thread-safe, they can be shared among multiple threads without restraint.
- Allows you to reason about a piece of code independently of the rest of the program because our internal state can't be changed by another part of our system.
- We can model things like they are, e.g. events - a fact that already happened, and we can't change the past.
§ Immutable collections
Immutable collections, like immutable objects, cannot be updated after creation.
The only way to add or remove an element is to create a new collection instance.
Immutable List in Java can be created using
List.of("a", "b", "c"),
any modification on this list will cause an exception.§ Immutable vs Mutable collections
We'll start with the main problem of mutable collections: they can be modified by anyone.
ShowStats getShowStats(List<Reservation> reservations) {
int activeReservations = calculateActiveReservations(reservations);
int totalReservations = reservations.size();
return new ShowStats(activeReservations, totalReservations);
}At first glance, it looks fine, but what if
calculateActiveReservations() removes some elements from the provided list?public int calculateActiveReservations(List<Reservation> reservations) {
reservations.removeIf(reservation -> reservation.status() != ReservationStatus.ACTIVE);
return reservations.size();
}If we pass an
ArrayList the method will modify the list and that will cause a bugShowStats getShowStats(List<Reservation> reservations) {
// reservations = [Reservation[status=ACTIVE], Reservation[status=ACTIVE], Reservation[status=CANCELLED]]
int activeReservations = calculateActiveReservations(reservations); // 2
// reservations = [Reservation[status=ACTIVE], Reservation[status=ACTIVE]]
int totalReservations = reservations.size(); // 2, and it should be 3
return new ShowStats(activeReservations, totalReservations);
}If we create a list using
List.of() it will create ImmutableCollections.List,
and Stream#toList() wraps the result with Collections.unmodifiableList.
Neither of them allows modification, both inform us about that through an UnsupportedOperationException.public int calculateActiveReservations(List<Reservation> reservations) { // List.of();
reservations.removeIf(reservation -> reservation.status() != ReservationStatus.ACTIVE); // UnsupportedOperationException
return reservations.size();
}The catch is that we can't demand such a list in the signature.
List.of() and new ArrayList<>() both give us a java.util.List, so the type says nothing about mutability -
the JDK simply has no type for an immutable list.
Until we reach for one, the best we can do is to copy the list at the boundary and work on our own instance.ShowStats getShowStats(List<Reservation> reservations) {
var safeReservations = List.copyOf(reservations);
int activeReservations = calculateActiveReservations(safeReservations);
int totalReservations = safeReservations.size();
return new ShowStats(activeReservations, totalReservations);
}But there are a few problems with standard "immutable" Java collections:
- The behavior seems more like read-only than immutable. An immutable collection should let us add an element and return a new collection, instead of refusing the operation.
- They report illegal operations at runtime, not at compile time.
So let's see how else we can approach the subject.
For example, in Kotlin
List interface doesn't contain methods like add, remove, etc.
And that sounds much more reasonable than throwing UnsupportedOperationException,
because we are held back by the compiler at the development stage.val readOnlyList: List<String> = listOf("a")
readOnlyList.add("b") // doesn't work, there is no method like 'add'To modify a list we need to define it explicitly as
MutableListval mutableList: MutableList<String> = arrayListOf("a")
mutableList.add("b")It's better, but not perfect.
Kotlin's
List is a read-only view, not an immutable collection.
The object behind it may still be an ArrayList, and whoever holds that reference can modify it -
val list: List<String> = arrayListOf("a") compiles just fine.
The compiler protects us from our own mistakes, not from aliasing.On top of that, adding elements should be allowed,
but it should create a new list containing values from the source list and the newly added value.
But won't it be slow?
Not for the operation we care about - we don't have to copy all values to the new list.
Instead, when we add a value, we create a new object that holds the new element and a reference to the previous list.
The new element becomes the head, and the whole previous list becomes the tail.
class ImmutableList<T> {
private final T head;
private final ImmutableList<T> tail;
ImmutableList(T head, ImmutableList<T> tail) {
this.head = head;
this.tail = tail;
}
ImmutableList<T> prepend(T element) {
return new ImmutableList<>(element, this);
}
}References
Adding an element this way is O(1), and so is reading the first one.
The cost shows up elsewhere: in a singly linked list like this one, random access and
size() are O(n),
so it's a poor fit for code that indexes into the collection in a loop.
Pick the structure after you know how the data is read, not because it's immutable.Unfortunately, such collections are not built in Java, so we need to use external libraries like Vavr.io
And that gives us back what the JDK couldn't express: with
io.vavr.collection.List in the signature
the caller can't hand us a mutable list, so the defensive copy from the beginning of this section becomes unnecessary.§ Functions
Functional programming is all about programming with functions.
We want our functions to be:
- Total. For every value of the input type, they return a valid output. No exceptions, no
null. - Pure. The result depends only on the arguments, and the function has no side effects. Same arguments, same result.
These are two separate properties.
Integer.parseInt("abc") is pure, but not total - it throws for some inputs.
A method that always returns a value but writes to a database is total, but not pure.Immutability is a third thing. It's a property of data, not of functions.
It doesn't make a function pure by itself, but it helps a lot - a function can't depend on state that changes.
Let's review a few methods and determine if they are total and pure.
class Account {
private BigDecimal balance;
void deposit(BigDecimal amount) {
if (amount.signum() <= 0) {
throw new IllegalArgumentException();
}
balance = balance.add(amount);
}
}As a rule of thumb, using
void is usually bad practice.
Methods that return void:- cannot be used in method chaining.
// deposit() returns nothing, so there is nothing to continue on
account.deposit(BigDecimal.valueOf(10))
.deposit(BigDecimal.valueOf(20)); // doesn't compile- Force to use exceptions for error handling.
- Are harder to test.
- Make it more difficult to track changes that have been made.
It's neither total nor pure.
It's not total, because it throws for amounts less than or equal to 0.
It's not pure, because it modifies
balance - that's a side effect.To make it total, we can introduce a new type that allows only to provide positive BigDecimals.
record PositiveBigDecimal(BigDecimal value) {
PositiveBigDecimal {
if (value.signum() <= 0) {
throw new IllegalArgumentException();
}
}
}The validation didn't disappear, it moved to the boundary of the type.
We pay for it once, when the value enters our system, and every method taking
PositiveBigDecimal can trust it.
So now our method signature forces us to use the appropriate parameter.void deposit(PositiveBigDecimal amount) {
balance = balance.add(amount.value());
}Now there is no input it can't handle.
Strictly speaking a
void method can't be total at all - totality is about returning an output for every input,
and here there is no output. We fixed the input side, the output side is still waiting.And it's still not pure, it still modifies
balance.Let's try to make it also pure.
What if we make this object immutable?
record Account(BigDecimal balance) {
Account deposit(PositiveBigDecimal amount) {
return new Account(balance.add(amount.value()));
}
}Careful with
BigDecimal inside records.
BigDecimal.equals compares the scale as well, so new Account(new BigDecimal("1.0"))
is not equal to new Account(new BigDecimal("1.00")), even though the amounts are the same.
A record derives equals from its components, so it inherits that behavior.
Compare amounts with compareTo, or normalize the scale when the value is created.You may say it's still not pure because it still depends on the internal state.
But what if we write it down like this:
static Account deposit(Account account, PositiveBigDecimal amount) {
return new Account(account.balance().add(amount.value()));
}As you see, we can just treat our object as the first argument of our function.
The internal state can't change, so the same account and amount always give the same result.
So the first approach is absolutely fine and can be acknowledged as pure. And it's still total.
Let's take a look at another example:
private final Map<Long, User> users = new HashMap<>();
User getUser(long id) {
return users.get(id);
}Is the function pure?
It's not, but not because it can return
null.
It reads users, which is not an argument and can be modified by any other method.
Call getUser(1), someone calls users.remove(1L), call getUser(1) again - same argument, different result.Is it total?
No. The signature says it returns a
User, but for an unknown id we get null.We can fix the second problem using the type system.
In this case
Optional seems reasonable.Optional<User> getUser(long id) {
return Optional.ofNullable(users.get(id));
}The missing user is now visible in the signature, not hidden behind
null, so the function is total.
But the function is still not pure - it still reads the mutable users map.
Optional solves the problem of representing a missing value, not purity.To make it pure, we have to pass the data as an argument:
static Optional<User> getUser(Map<Long, User> users, long id) {
return Optional.ofNullable(users.get(id));
}Now the result depends only on the arguments.
As long as the map we pass is immutable (e.g. created with
Map.copyOf()), the same arguments always give the same result.In a real application
users would be a database, and reading from a database is never pure.
That's fine - we can't avoid it, but we can keep such code at the edges and the rest of the logic pure.§ Working with Optional
For those not familiar with FP the most straightforward way to use
Optional will beOptional<User> userOpt = getUser(1);
if (userOpt.isPresent()) {
User user = userOpt.get();
}But it's not really how we do it functionally.
In most cases, we should avoid invoking
get().
We want to use map and flatMap operations.Bad ❌
public String displayUsername(long userId) {
Optional<User> userOpt = getUser(userId);
if (userOpt.isPresent()) {
return userOpt.get().getUsername();
}
return "Anonymous";
}→
Good ✅
public String displayUsername(long userId) {
return getUser(userId)
.map(User::getUsername)
.orElse("Anonymous");
}
The first piece of code is not perfect, but we can live with it.
Now imagine
User#getUsername returns Optional<String> instead of a plain String.Bad ❌
public String displayUsername(long userId) {
Optional<User> userOpt = getUser(userId);
if (userOpt.isPresent()) {
Optional<String> usernameOpt = userOpt.get().getUsername();
if (usernameOpt.isPresent()) {
return usernameOpt.get();
}
}
return "Anonymous";
}→
Good ✅
public String displayUsername(long userId) {
return getUser(userId)
.flatMap(User::getUsername)
.orElse("Anonymous");
}
§ Validation
The hidden behavior also applies to validation.
public User createUser(String name) {
if (name.length() < 3) {
throw new IllegalArgumentException("Name too short");
}
return new User(name);
}What's the problem here?
- The method signature hides from us the fact there is validation inside the method body.
- The compiler doesn't force us to handle errors.
- Exceptions are not an excellent choice for business errors, they are more for exceptional cases.
How to do it in a better way?
public Either<DomainError, User> createUser(String name) {
if (name.length() < 3) {
return Either.left(DomainError.NAME_TOO_SHORT);
}
return Either.right(new User(name));
}Either allows explicitly showing our method has two paths.
The success - right, and the failure - left.
References
Thanks to that:
- There's no need to examine the method code to identify alternative scenarios.
- compiler forces us to handle errors.
The second point is only true if we look at the calling side.
Either is not a checked exception, nothing stops us from ignoring it,
but we can't reach the User without saying what should happen with the error.ResponseEntity<?> register(String name) {
return createUser(name).fold(
error -> ResponseEntity.badRequest().body(error),
user -> ResponseEntity.ok(user.toDTO())
);
}Note that
createUser is still not total - it throws NullPointerException for null.
Either describes the errors we decided to model, it doesn't protect us from the ones we ignore.
The answer is a UserName type, so that the check happens once instead of in every method taking a String.And that brings us back to
PositiveBigDecimal from the previous section.
Its constructor throws, so creating the type was never total - we only moved the partiality out of deposit.
Either lets us make the creation total as well.record PositiveBigDecimal(BigDecimal value) {
PositiveBigDecimal {
if (value.signum() <= 0) {
throw new IllegalArgumentException();
}
}
static Either<DomainError, PositiveBigDecimal> of(BigDecimal value) {
if (value == null || value.signum() <= 0) {
return Either.left(DomainError.AMOUNT_NOT_POSITIVE);
}
return Either.right(new PositiveBigDecimal(value));
}
}The constructor stays as a guard against our own bugs, but the application code goes through
of,
which handles every BigDecimal we can throw at it. The validation happens once, at the edge,
and from that point on the type carries the proof.This shape has a name - a smart constructor: a guarded constructor plus a factory that returns the error
instead of throwing it.
UserName works exactly the same way.Another interesting class is
Validation. Like Either, Validation contains two paths, valid and invalid.
The main difference is that instead of stopping at the first failure, Validation runs all the checks and accumulates their errors.References
To demonstrate the usage, let's write a code for loading CSV files.
A flight is just a pair of airport codes.
record Flight(String departure, String destination) {
}List<Flight> load(List<String> lines) {
return lines.stream().map(this::parse).toList();
}
private Flight parse(String line) {
var args = line.split(",");
String departure = args[0];
if (!isValidIcaoCode(departure)) {
throw new IllegalArgumentException("Departure is not valid ICAO airport code.");
}
String destination = args[1];
if (!isValidIcaoCode(destination)) {
throw new IllegalArgumentException("Destination is not valid ICAO airport code.");
}
return new Flight(departure, destination);
}
private boolean isValidIcaoCode(String icaoCode) {
return icaoCode.length() == 4;
}Let's imagine we want to upload a CSV file with hundreds of rows and some of them contain errors.
Do you see a problem with the above solution?
If there are errors in our CSV file we won't be informed about all errors at once, but only about the first one.
In this case, a list of errors would be handier.
For that purpose, we can use
Validation from Vavr.Note that from now on
List and Seq come from io.vavr.collection,
because we need a map operation on the collection itself.Seq<Validation<Seq<String>, Flight>> load(Seq<String> lines) {
return lines.map(this::parse);
}
private Validation<Seq<String>, Flight> parse(String line) {
var args = line.split(",");
String departure = args[0];
String destination = args[1];
return Validation.combine(
validateIcaoCode(departure),
validateIcaoCode(destination)
).ap(Flight::new);
}
private Validation<String, String> validateIcaoCode(String icao) {
if (icao.length() == 4) {
return Validation.valid(icao);
}
return Validation.invalid("%s is not valid ICAO code".formatted(icao));
}Our code didn't change much. Instead of throwing an exception, we just return an object, so the flow is not terminated instantly.
The loading part is more problematic because we have to handle
Seq<Validation<Seq<String>, Flight>>.
The question is how to aggregate the data to easily display the number of loaded flights or the list of validation errors.
For the sake of our sanity, there is Validation#sequence which:Reduces many Validation instances into a single Validation by transforming anIterable<Validation<? extends T>>into aValidation<Seq<T>>.
That is the javadoc, and it is out of date with its own signature.
The method is declared as
Validation<Seq<E>, Seq<T>> sequence(Iterable<? extends Validation<? extends Seq<? extends E>, ? extends T>> values),
so the errors are accumulated as well - which is exactly what we need here.Validation<Seq<String>, Seq<Flight>> result = Validation.sequence(load(lines));
String message = result.fold(
strings -> strings.mkString("Failed to load flights: \n", "\n", ""),
flights -> "Successfully loaded " + flights.size() + " flights."
);Thanks to transforming to single
Validation we can easily tell if the whole operation succeeds or not.
We utilize <U> U fold(Function<? super E, ? extends U> ifInvalid, Function<? super T, ? extends U> ifValid) to map errors and flights to the same type.§ Functional iceberg
We've only touched the basics. There is much more in the world of functional programming, but Java doesn't have decent support for that.
And often Java programmers are not very familiar with this paradigm. That's why functional programming can become a double-edged sword.
return Mono.fromCallable(
() -> pullEVSEDataToKafkaSynchronizationTransformer.transformEntitiesToEvents(entityList, operatorId)
)
.zipWith(statuses)
.map(
tuple -> {
tuple.getT1().forEach(
event -> event.getOcpiLocation().getEvses().forEach(
evse -> Optional.ofNullable(tuple.getT2().get(evse.getEvseId()))
.map(EvseStatusRecord::getEvseStatus)
.ifPresentOrElse(
status -> evse.setStatus(OcpiEvseStatusPatchedEventBuilder.mapStatus(status)),
() -> evse.setStatus(OcpiEvse.Status.UNKNOWN)
)
)
);
return tuple;
}
)
.flatMapMany(tuple -> sendEventToKafkaAndUpdateDb(tuple.getT1()))
.then(
Flux.fromIterable(entityList)
.map(
entity -> {
entity.setSyncedKafka(Boolean.TRUE);
return entity;
}
)
.limitRate(500)
.map(SqlQueryBuilder::buildSavePullEvseDataQuery)
.buffer(500)
.concatMap(sqlList -> evseDataReactiveClientRepository.saveAll(sqlList))
.reduce(NumberUtils.INTEGER_ZERO, (integer, integer2) -> integer + integer2)
);That's not all.
The real "fun" begins when we mix stuff like
Mono and Eitherpublic Mono<Either<AppError, UserDTO>> registerUser(RegisterUserDTO dto) {
return userFactory
.create(dto.username(), dto.password(), UserRole.COMMON)
.flatMap(it -> it
.map(user -> reactiveUserRepository
.add(user)
.map(u -> Either.<AppError, UserDTO>right(u.toDTO()))
)
.mapLeft(error -> Mono.just(Either.<AppError, UserDTO>left(error))).getOrElse(error -> error)
);
}References
So in Java, I would stick to the basics; otherwise, your colleagues might hate you.
§ Summary
We have learned several key concepts of functional programming. These basics are well-supported by the language and should not disturb our team members.
- Immutability should be our default choice. Use record classes, and the same goes for collections, although you may already be doing this, perhaps unknowingly?
List.ofreturnsImmutableCollections.List,Stream#toList()returnsCollections.unmodifiableList. Just remember those are read-only, not immutable, and the JDK has no type to demand one - at an API boundary we still needList.copyOf, or a library like Vavr. - Total and pure are two separate properties. A method can return a value for every input and still touch the world, and the other way around.
- Wrap values in types that validate once, at the edge:
PositiveBigDecimalinstead ofBigDecimal,UserNameinstead ofString. Every method downstream can then trust its arguments. - For domain errors, prefer
EitherandValidation. The latter allows holding a list of errors. Reserve exceptions for exceptional situations. - Avoid
void.
Functional Programming offers us much more, but as Java developers, we can't really apply more advanced concepts to our projects.
So, we have to decide if we want to complain about the missing features or live in blissful ignorance.
