Vavr is a functional programming library for Java that provides immutable collections, functional control structures, and more. Here's an example of using the Vavr library to create an immutable list of integers and then performing some operations on it:
import io.vavr.collection.List;
public class VavrExample {
public static void main(String[] args) {
// Create an immutable list of integers
List<Integer> numbers = List.of(1, 2, 3, 4, 5);
// Print the list
System.out.println("Numbers: " + numbers);
// Double all the numbers in the list using the map() method
List<Integer> doubledNumbers = numbers.map(n -> n * 2);
// Print the doubled list
System.out.println("Doubled Numbers: " + doubledNumbers);
// Filter the even numbers from the list using the filter() method
List<Integer> evenNumbers = numbers.filter(n -> n % 2 == 0);
// Print the even numbers list
System.out.println("Even Numbers: " + evenNumbers);
}
}
In this example, we first create an immutable list of integers using the List.of() method provided by the Vavr library. We then print the list to the console.
Next, we use the map() method to double all the numbers in the list, creating a new list of doubled numbers. We print the doubled list to the console.
Finally, we use the filter() method to create a new list that contains only the even numbers from the original list. We print this even numbers list to the console as well.
Note that because the list is immutable, the original list is not modified by any of these operations. Instead, each operation returns a new list that represents the result of that operation. This is one of the key features of the Vavr library, as it makes it easier to reason about your code and avoid bugs that can arise from mutable state.
Comments