Posts

Showing posts with the label Java Functional Programming

Reactive Programming – with Project Reactor or RxJava

Reactive Programming – with Project Reactor or RxJava Reactive programming is a programming paradigm that deals with asynchronous data streams. Instead of executing tasks in a sequential manner, reactive programming allows you to manage streams of data asynchronously, making your programs more efficient and scalable. Two of the most popular libraries for reactive programming in Java are Project Reactor and RxJava . 🌍 What is Reactive Programming? Reactive programming focuses on building systems that are event-driven, non-blocking, and scalable. It allows for handling asynchronous data streams (such as events, network responses, or user input) in a declarative way. Reactive systems are inherently more responsive, resilient, and elastic. The key concepts in reactive programming are: Observable Streams : Data that is asynchronously emitted over time. Operators : Functions that allow you to manipulate the streams. Backp...

Java Streams: map() vs flatMap()

Java Streams: map() vs flatMap() In Java Streams, both map() and flatMap() are used to transform data — but they behave differently based on the output structure. Let's break it down with real examples. ✅ map() – One-to-One Transformation Transforms each element into another value (e.g., String to Integer ): List<String> names = List.of("Alice", "Bob"); List<Integer> lengths = names.stream() .map(String::length) .collect(Collectors.toList()); System.out.println(lengths); // Output: [5, 3] ✅ flatMap() – One-to-Many Flattening Each element is mapped to a Stream , and all streams are then flattened into a single stream: List<String> sentences = List.of("Hello world", "Java Streams"); List<String> words = sentences.stream() .flatMap(s -> Arrays.stream(s.split(" "))) .collect(Collectors.toList()); System.out.println(words);...

Java Streams: A Modern Way to Process Data

Java Streams: A Modern Way to Process Data Introduced in Java 8, the Stream API brings a functional approach to processing collections. With streams, you can perform operations like filtering , mapping , and reducing in a concise and readable way. 🔍 What is a Stream? A Stream represents a sequence of elements and supports sequential and parallel aggregate operations. List<String> names = Arrays.asList("Alice", "Bob", "Charlie"); names.stream() .filter(name -> name.startsWith("A")) .forEach(System.out::println); Output: Alice ⚙️ Common Operations 1. filter() Filters elements based on a condition: List<Integer> nums = Arrays.asList(1, 2, 3, 4, 5); nums.stream() .filter(n -> n % 2 == 0) .forEach(System.out::println); 2. map() Transforms each element: List<String> names = Arrays.asList("Java", "Pytho...