Unlock Functional Java with Vavr: Immutable Collections & Pattern Matching
This article introduces Vavr, a Java 8 functional library that brings immutable, persistent collections, observable side‑effects via Try, tuple types, enhanced function composition, lazy evaluation, and Scala‑like pattern matching, showing code examples and explaining how to integrate the library into Maven projects.
Vavr
Vavr is a functional library for Java 8 that brings many functional programming paradigms, offering persistent data structures and functional control structures.
Observable side effects
Traditional code can hide side‑effects such as division by zero. Vavr wraps such operations in a Try container, making failures explicit. int divide(int a, int b){ return a/b; } Using Vavr:
Try<Integer> divide(Integer a, Integer b){ return Try.of(() -> a / b); }The Try<Integer> result signals a possible failure that can be handled safely.
Immutable data structures
Immutable values are thread‑safe, reliable for equals / hashCode, require no cloning, and are type‑safe in unchecked casts. Vavr provides a collection library that replaces Java’s standard collections with persistent, immutable structures built on lambdas.
All Vavr collections implement Iterable and are persistent: once created they never change, and operations return new instances. List<Integer> source = List.of(1, 2, 3); Adding an element creates a new list while the original remains unchanged:
List<Integer> newHeadList = source.tail().prepend(0); // 0 2 3
System.out.println(source); // 1 2 3 List<Integer> prepend = source.prepend(0); // 0 1 2 3
List<Integer> append = source.append(0); // 1 2 3 0Tuples
Vavr offers immutable tuples of up to eight elements, similar to Python’s tuples.
Tuple2<String, Integer> java8 = Tuple.of("felord.cn", 22);
String s = java8._1; // "felord.cn"
Integer i = java8._2; // 22“This can be used to simulate multiple return values in Java.”
Function
Vavr extends Java’s Function interfaces with richer combinators, allowing composition, lifting, and currying.
Function1<Integer, Integer> multiplyByTwo = a -> a * 2;
Function1<Integer, Integer> compose = multiplyByTwo.compose(a -> a + 1);
Integer result = compose.apply(2); // 6 Function2<Integer, Integer, Integer> divide = (a, b) -> a / b;
Function2<Integer, Integer, Option<Integer>> safeDivide = Function2.lift(divide);
Option<Integer> opt = safeDivide.apply(1, 0);
boolean empty = opt.isEmpty(); // true Function2<Integer, Integer, Integer> divide = (a, b) -> a / b;
Function1<Integer, Integer> partially = divide.apply(4);
Integer r = partially.apply(2); // 2 Function3<Integer, Integer, Integer, Integer> sum = (a, b, c) -> a + b + c;
Function1<Integer, Function1<Integer, Integer>> add2 = sum.curried().apply(1);
Integer total = add2.apply(2).apply(3); // 6Pattern matching
Vavr provides a Scala‑like pattern‑matching API that reduces boilerplate compared with chained if‑else statements.
public static String vavrMatch(int input){
return Match(input).of(
Case($(1), "one"),
Case($(2), "two"),
Case($(3), "three"),
Case($(), "unknown")
);
}Special value containers
Vavr includes containers such as Option (a richer alternative to Optional) and Lazy for lazy evaluation.
Lazy<Double> lazy = Lazy.of(Math::random);
lazy.isEvaluated(); // false
double d = lazy.get(); // computed once
lazy.isEvaluated(); // trueConclusion
Functional programming is a major highlight of Java 8. Starting with Vavr helps developers adopt functional concepts such as immutable data, explicit side‑effects, and pattern matching. To add Vavr to a Maven project, use the following dependency:
<!-- https://mvnrepository.com/artifact/io.vavr/vavr -->
<dependency>
<groupId>io.vavr</groupId>
<artifactId>vavr</artifactId>
<version>0.10.3</version>
</dependency>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.
Programmer DD
A tinkering programmer and author of "Spring Cloud Microservices in Action"
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.
