<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Programming &#8211; Mastering the Art of Java Programming</title>
	<atom:link href="https://blog.j-dev.app/category/programming/feed/" rel="self" type="application/rss+xml" />
	<link>https://blog.j-dev.app</link>
	<description>Unleashing the Power of a Versatile Language</description>
	<lastBuildDate>Wed, 21 Feb 2024 17:28:16 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	

<image>
	<url>https://blog.j-dev.app/wp-content/uploads/2023/08/cropped-DALL·E-2023-06-27-1b-32x32.png</url>
	<title>Programming &#8211; Mastering the Art of Java Programming</title>
	<link>https://blog.j-dev.app</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Java in Parallel: A Detailed Guide to Concurrency and Multithreading</title>
		<link>https://blog.j-dev.app/java-guide-to-concurrency-and-multithreading/</link>
		
		<dc:creator><![CDATA[JuanC]]></dc:creator>
		<pubDate>Thu, 21 Sep 2023 05:43:59 +0000</pubDate>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Concurrency]]></category>
		<category><![CDATA[Guide]]></category>
		<category><![CDATA[Multithreading]]></category>
		<category><![CDATA[Threads]]></category>
		<guid isPermaLink="false">https://blog.j-dev.app/?page_id=207</guid>

					<description><![CDATA[1. Introduction to Concurrency and Multithreading 1.1 Definition of Concurrency Concurrency, in the realm of computer science, refers to the ability of a computer system or an application to perform more than one task simultaneously. It doesn&#8217;t necessarily mean that multiple processes are executing at the exact same instant; rather, it means that more than [&#8230;]]]></description>
										<content:encoded><![CDATA[
<h2 class="wp-block-heading">1. Introduction to Concurrency and Multithreading</h2>



<h3 class="wp-block-heading">1.1 Definition of Concurrency</h3>



<p>Concurrency, in the realm of computer science, refers to the ability of a computer system or an application to perform more than one task simultaneously. It doesn&#8217;t necessarily mean that multiple processes are executing at the exact same instant; rather, it means that more than one task is progressing in overlapping time frames.</p>



<p>In Java, concurrency is achieved through the concurrent execution of threads. Threads are the smallest unit of execution within a process, and a Java program can spawn multiple threads to execute different tasks simultaneously, thus utilizing concurrency. This ability to carry out multiple operations concurrently, instead of sequentially, can greatly enhance the performance and responsiveness of an application, especially when it is designed to perform a large number of non-dependent tasks.</p>



<p>Understanding concurrency is foundational in Java programming because it allows developers to write programs that are more efficient and responsive, and that can leverage the multi-core architecture of modern CPUs to its fullest.</p>



<h3 class="wp-block-heading">1.2 Definition of Multithreading</h3>



<p>Multithreading is a specific form of concurrency that involves the concurrent execution of multiple threads. A thread, which is the smallest unit of execution within a process, is a sequence of executed instructions that can be managed independently by a scheduler.</p>



<p>In the context of Java, multithreading is facilitated by the Java Virtual Machine (JVM), which manages the execution of multiple threads within a single process. This allows a Java program to perform several tasks simultaneously, enhancing its efficiency and performance. Multithreading leverages CPU cores optimally by allowing multiple threads to run in parallel, thereby utilizing the computational resources proficiently.</p>



<p>Java provides built-in support for multithreaded programming through its <code>java.lang.Thread</code> class and <code>java.lang.Runnable</code> interface, among other utilities, providing programmers a robust and flexible environment for implementing multithreaded applications.</p>



<h3 class="wp-block-heading">1.3 Why is Concurrency Important?</h3>



<p>Concurrency is crucial in modern computing for several reasons:</p>



<ul class="wp-block-list">
<li><strong>Performance</strong>: Concurrent programs can execute more efficiently on multi-core processors, as different threads can run on different cores simultaneously, reducing the total execution time.</li>



<li><strong>Responsiveness</strong>: In graphical user interface (GUI) applications, concurrency ensures that the application remains responsive even while performing intensive operations in the background.</li>



<li><strong>Resource Utilization</strong>: Concurrency enables better utilization of system resources by allowing I/O operations to overlap with computational tasks, thereby reducing idle time and enhancing throughput.</li>



<li><strong>Structure</strong>: Concurrent programs can be structured more clearly and modularly, facilitating cleaner and more maintainable code, especially when different tasks within an application are naturally independent of each other.</li>
</ul>



<p>Understanding and leveraging concurrency is, therefore, a vital skill in Java programming, helping to develop applications that are fast, responsive, and resource-efficient.</p>



<h3 class="wp-block-heading">1.4 The Challenges of Concurrency</h3>



<p>While concurrency brings many benefits, it also introduces a set of challenges that developers must navigate:</p>



<ul class="wp-block-list">
<li><strong>Complexity</strong>: Concurrent programs are generally more complex to write, understand, and debug compared to sequential programs due to the overlapping execution of threads.</li>



<li><strong>Deadlocks</strong>: These occur when two or more threads are unable to proceed because each is waiting for the other to release a lock. Deadlocks can be challenging to identify and resolve.</li>



<li><strong>Race Conditions</strong>: A race condition happens when the outcome of a process is affected by the timing or ordering of other uncontrollable events. It becomes a bug when events do not happen in the order the programmer intended, leading to undesirable behaviors.</li>



<li><strong>Resource Contention</strong>: When multiple threads attempt to access shared resources concurrently, it can lead to resource contention, causing delays and reducing the performance benefits of concurrency.</li>
</ul>



<p>Given these challenges, mastering concurrency in Java involves not just leveraging its benefits but also effectively mitigating its inherent complexities through careful design and coding, and meticulous testing and debugging.</p>



<h2 class="wp-block-heading">2. Understanding Threads in Java</h2>



<h3 class="wp-block-heading">2.1 Overview of Threads</h3>



<p>In the Java programming language, a thread is a lightweight subprocess or a path of execution that runs concurrently with other threads within a program. Each thread operates independently but shares the same memory space and resources of the application. The use of threads allows a program to perform multiple operations simultaneously, improving performance and enabling more interactive and fluid applications.</p>



<p>Threads are an integral part of Java, with every Java application having at least one thread, known as the main thread. The main thread is the entry point to your application where the initial instructions are executed. Moreover, threads play a crucial role in the development of real-time applications, server applications, and complex systems, where efficient resource utilization and high responsiveness are paramount.</p>



<h3 class="wp-block-heading">2.2 Creating Threads in Java</h3>



<p>In Java, threads can be created in two primary ways:</p>



<ul class="wp-block-list">
<li><strong>By Extending the Thread Class</strong>: You create a new class that extends the <code>Thread</code> class and overrides its <code>run()</code> method where you define the code that should be executed in the thread. Once your class is ready, you can create an instance of your class and call the <code>start()</code> method to begin the thread execution. For instance:</li>
</ul>



<div class="wp-block-kevinbatdorf-code-block-pro" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:clamp(14px, .875rem, 21px);font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:clamp(20px, 1.25rem, 30px);--cbp-tab-width:4;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:10px 0px 10px 16px;margin-bottom:-2px;width:100%;text-align:left;background-color:#2f363c;color:#d3d7dd">Java</span><span role="button" tabindex="0" data-code="class MyThread extends Thread {
	@Override
    public void run(){
        System.out.println(&quot;Thread is running...&quot;);
    }
}

public class Example{
    public static void main(String args[]) {
        MyThread t1 = new MyThread();
        t1.start();
    }
}" style="color:#e1e4e8;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki github-dark" style="background-color: #24292e" tabindex="0"><code><span class="line"><span style="color: #F97583">class</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">MyThread</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">extends</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">Thread</span><span style="color: #E1E4E8"> {</span></span>
<span class="line"><span style="color: #E1E4E8">	@</span><span style="color: #F97583">Override</span></span>
<span class="line"><span style="color: #E1E4E8">    </span><span style="color: #F97583">public</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">void</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">run</span><span style="color: #E1E4E8">(){</span></span>
<span class="line"><span style="color: #E1E4E8">        System.out.</span><span style="color: #B392F0">println</span><span style="color: #E1E4E8">(</span><span style="color: #9ECBFF">&quot;Thread is running...&quot;</span><span style="color: #E1E4E8">);</span></span>
<span class="line"><span style="color: #E1E4E8">    }</span></span>
<span class="line"><span style="color: #E1E4E8">}</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F97583">public</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">class</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">Example</span><span style="color: #E1E4E8">{</span></span>
<span class="line"><span style="color: #E1E4E8">    </span><span style="color: #F97583">public</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">static</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">void</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">main</span><span style="color: #E1E4E8">(String </span><span style="color: #FFAB70">args</span><span style="color: #E1E4E8">[]) {</span></span>
<span class="line"><span style="color: #E1E4E8">        MyThread t1 </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">new</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">MyThread</span><span style="color: #E1E4E8">();</span></span>
<span class="line"><span style="color: #E1E4E8">        t1.</span><span style="color: #B392F0">start</span><span style="color: #E1E4E8">();</span></span>
<span class="line"><span style="color: #E1E4E8">    }</span></span>
<span class="line"><span style="color: #E1E4E8">}</span></span></code></pre></div>



<ul class="wp-block-list">
<li><strong>By Implementing the Runnable Interface</strong>: You create a new class that implements the <code>Runnable</code> interface and its <code>run()</code> method. This class is then passed as a parameter to a Thread instance which can then be started using the <code>start()</code> method. For example:</li>
</ul>



<div class="wp-block-kevinbatdorf-code-block-pro" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:clamp(14px, .875rem, 21px);font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:clamp(20px, 1.25rem, 30px);--cbp-tab-width:4;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:10px 0px 10px 16px;margin-bottom:-2px;width:100%;text-align:left;background-color:#2f363c;color:#d3d7dd">Java</span><span role="button" tabindex="0" data-code="class MyRunnable implements Runnable {
	@Override
    public void run(){
        System.out.println(&quot;Runnable is running...&quot;);
    }
}

public class Example {
    public static void main(String args[]){
        MyRunnable r1 = new MyRunnable();
        Thread t1 = new Thread(r1);
        t1.start();
    }
}" style="color:#e1e4e8;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki github-dark" style="background-color: #24292e" tabindex="0"><code><span class="line"><span style="color: #F97583">class</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">MyRunnable</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">implements</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">Runnable</span><span style="color: #E1E4E8"> {</span></span>
<span class="line"><span style="color: #E1E4E8">	@</span><span style="color: #F97583">Override</span></span>
<span class="line"><span style="color: #E1E4E8">    </span><span style="color: #F97583">public</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">void</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">run</span><span style="color: #E1E4E8">(){</span></span>
<span class="line"><span style="color: #E1E4E8">        System.out.</span><span style="color: #B392F0">println</span><span style="color: #E1E4E8">(</span><span style="color: #9ECBFF">&quot;Runnable is running...&quot;</span><span style="color: #E1E4E8">);</span></span>
<span class="line"><span style="color: #E1E4E8">    }</span></span>
<span class="line"><span style="color: #E1E4E8">}</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F97583">public</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">class</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">Example</span><span style="color: #E1E4E8"> {</span></span>
<span class="line"><span style="color: #E1E4E8">    </span><span style="color: #F97583">public</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">static</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">void</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">main</span><span style="color: #E1E4E8">(String </span><span style="color: #FFAB70">args</span><span style="color: #E1E4E8">[]){</span></span>
<span class="line"><span style="color: #E1E4E8">        MyRunnable r1 </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">new</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">MyRunnable</span><span style="color: #E1E4E8">();</span></span>
<span class="line"><span style="color: #E1E4E8">        Thread t1 </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">new</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">Thread</span><span style="color: #E1E4E8">(r1);</span></span>
<span class="line"><span style="color: #E1E4E8">        t1.</span><span style="color: #B392F0">start</span><span style="color: #E1E4E8">();</span></span>
<span class="line"><span style="color: #E1E4E8">    }</span></span>
<span class="line"><span style="color: #E1E4E8">}</span></span></code></pre></div>



<p>Understanding these methods is essential as it gives you the foundation to create multithreaded applications in Java.</p>



<h3 class="wp-block-heading">2.3 Thread Lifecycle</h3>



<p>The life cycle of a thread in Java involves several states, and a thread can be in one of the following states at a given point in time:</p>



<ol class="wp-block-list">
<li><strong>New</strong>: A thread is in this state when an instance of the Thread class is created but the <code>start()</code> method hasn&#8217;t been called yet.</li>



<li><strong>Runnable</strong>: Once the <code>start()</code> method is invoked, the thread moves to the runnable state. It may or may not be selected for running by the scheduler.</li>



<li><strong>Running</strong>: The thread is in this state when it is currently executing.</li>



<li><strong>Blocked/Waiting</strong>: In this state, the thread is alive but not eligible to run due to waiting for a lock or other resources to become available.</li>



<li><strong>Terminated/Dead</strong>: The thread enters this state once it completes its execution or if it is forcibly stopped.</li>
</ol>



<p>Understanding the lifecycle of a thread is essential to managing threads effectively in a Java application, helping you to control the execution flow and handle synchronization and concurrency issues appropriately.</p>



<h3 class="wp-block-heading">2.4 Thread Priorities</h3>



<p>In Java, threads can be assigned priorities on a scale from 1 to 10, where 1 is the lowest priority and 10 is the highest. By default, every thread is given a priority of 5. You can change the priority of a thread using the <code>setPriority(int)</code> method. The thread scheduler uses thread priorities to decide which thread should be executed first.</p>



<p>Threads with higher priority are generally given precedence over threads with lower priority. However, setting the thread priority does not guarantee the order of execution as it is highly platform-dependent. For instance:</p>



<div class="wp-block-kevinbatdorf-code-block-pro" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:clamp(14px, .875rem, 21px);font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:clamp(20px, 1.25rem, 30px);--cbp-tab-width:4;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:10px 0px 10px 16px;margin-bottom:-2px;width:100%;text-align:left;background-color:#2f363c;color:#d3d7dd">Java</span><span role="button" tabindex="0" data-code="Thread t1 = new Thread();
t1.setPriority(Thread.MAX_PRIORITY); // Setting the priority to 10" style="color:#e1e4e8;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki github-dark" style="background-color: #24292e" tabindex="0"><code><span class="line"><span style="color: #E1E4E8">Thread t1 </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">new</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">Thread</span><span style="color: #E1E4E8">();</span></span>
<span class="line"><span style="color: #E1E4E8">t1.</span><span style="color: #B392F0">setPriority</span><span style="color: #E1E4E8">(Thread.MAX_PRIORITY); </span><span style="color: #6A737D">// Setting the priority to 10</span></span></code></pre></div>



<p>Understanding thread priorities is important in Java programming, especially in scenarios where certain threads are more critical than others, and you wish to control the relative execution order of threads to optimize the performance of your application.</p>



<h2 class="wp-block-heading">3. Synchronization in Java</h2>



<h3 class="wp-block-heading">3.1 The Concept of Synchronization</h3>



<p>Synchronization in Java refers to the capability to control the access of multiple threads to any shared resource. It helps in preventing thread interference and memory consistency errors. In a multithreaded environment, synchronization becomes indispensable to secure an application from bugs and errors that stem from concurrent access to shared resources. The chief idea behind synchronization is to allow only one thread to access a shared resource at a given time, ensuring a safer and bug-free execution environment. Synchronization can be achieved through various means, including synchronized methods, synchronized blocks, and static synchronization, which will be detailed in the following subsections.</p>



<h3 class="wp-block-heading">3.2 Synchronized Methods</h3>



<p>In Java, methods can be synchronized by using the <code>synchronized</code> keyword. When a method is synchronized, it locks the object&#8217;s monitor for the duration of the method call, allowing only one thread to execute the method at a time. Other threads that attempt to call the method on the same object will be blocked until the method is released by the current executing thread.</p>



<div class="wp-block-kevinbatdorf-code-block-pro" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:clamp(14px, .875rem, 21px);font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:clamp(20px, 1.25rem, 30px);--cbp-tab-width:4;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:10px 0px 10px 16px;margin-bottom:-2px;width:100%;text-align:left;background-color:#2f363c;color:#d3d7dd">Java</span><span role="button" tabindex="0" data-code="public synchronized void synchronizedMethod() {
    // method body
}" style="color:#e1e4e8;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki github-dark" style="background-color: #24292e" tabindex="0"><code><span class="line"><span style="color: #F97583">public</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">synchronized</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">void</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">synchronizedMethod</span><span style="color: #E1E4E8">() {</span></span>
<span class="line"><span style="color: #E1E4E8">    </span><span style="color: #6A737D">// method body</span></span>
<span class="line"><span style="color: #E1E4E8">}</span></span></code></pre></div>



<p>In the above code snippet, the <code>synchronizedMethod</code> is synchronized at the object level; any thread attempting to invoke any synchronized method on the same object will be blocked.</p>



<p>By using synchronized methods, you can prevent race conditions and ensure that your methods are atomic, meaning that they operate as a single indivisible unit of operation, securing the integrity of the object&#8217;s state.</p>



<h3 class="wp-block-heading">3.3 Synchronized Blocks</h3>



<p>Synchronized blocks are used to mark a particular section of the code as synchronized, rather than synchronizing the entire method. This offers a finer level of control over synchronization, allowing you to minimize the scope of the lock, thereby reducing the overhead of synchronization.</p>



<div class="wp-block-kevinbatdorf-code-block-pro" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:clamp(14px, .875rem, 21px);font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:clamp(20px, 1.25rem, 30px);--cbp-tab-width:4;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:10px 0px 10px 16px;margin-bottom:-2px;width:100%;text-align:left;background-color:#2f363c;color:#d3d7dd">Java</span><span role="button" tabindex="0" data-code="public void synchronizedBlock() {
    synchronized(this) {
        // synchronized block
    }
}" style="color:#e1e4e8;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki github-dark" style="background-color: #24292e" tabindex="0"><code><span class="line"><span style="color: #F97583">public</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">void</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">synchronizedBlock</span><span style="color: #E1E4E8">() {</span></span>
<span class="line"><span style="color: #E1E4E8">    </span><span style="color: #F97583">synchronized</span><span style="color: #E1E4E8">(</span><span style="color: #79B8FF">this</span><span style="color: #E1E4E8">) {</span></span>
<span class="line"><span style="color: #E1E4E8">        </span><span style="color: #6A737D">// synchronized block</span></span>
<span class="line"><span style="color: #E1E4E8">    }</span></span>
<span class="line"><span style="color: #E1E4E8">}</span></span></code></pre></div>



<p>In the above example, the synchronized block is synchronized on <code>this</code> object. However, you can choose to synchronize the block on any other object. This is beneficial when you want to guard against concurrent access to a smaller section of code while allowing more flexibility and performance optimization in multi-threaded environments.</p>



<h3 class="wp-block-heading">3.4 Static Synchronization</h3>



<p>Static synchronization is the process of synchronizing static methods. In static synchronization, the lock is on the class object, not on the individual object instances. Since static methods belong to the class rather than to any specific instance, this ensures that all instances of the class will respect the lock, preventing concurrent access to the static method.</p>



<div class="wp-block-kevinbatdorf-code-block-pro" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:clamp(14px, .875rem, 21px);font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:clamp(20px, 1.25rem, 30px);--cbp-tab-width:4;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:10px 0px 10px 16px;margin-bottom:-2px;width:100%;text-align:left;background-color:#2f363c;color:#d3d7dd">Java</span><span role="button" tabindex="0" data-code="public static synchronized void staticSynchronizedMethod() {
    // method body
}" style="color:#e1e4e8;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki github-dark" style="background-color: #24292e" tabindex="0"><code><span class="line"><span style="color: #F97583">public</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">static</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">synchronized</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">void</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">staticSynchronizedMethod</span><span style="color: #E1E4E8">() {</span></span>
<span class="line"><span style="color: #E1E4E8">    </span><span style="color: #6A737D">// method body</span></span>
<span class="line"><span style="color: #E1E4E8">}</span></span></code></pre></div>



<p>In the above code snippet, the <code>staticSynchronizedMethod</code> is a static method synchronized using the <code>synchronized</code> keyword, allowing only one thread to access this method across all instances of the class.</p>



<p>Static synchronization is pivotal when you work with static data members of the class, ensuring a consistent and thread-safe behavior when accessing shared static variables.</p>



<p>By leveraging static synchronization, you shield your static methods from concurrent access, offering a robust mechanism to preserve the consistency and integrity of the static state of the class.</p>



<h2 class="wp-block-heading">4. Inter-thread Communication</h2>



<h3 class="wp-block-heading">4.1 Understanding Inter-thread Communication</h3>



<p>Inter-thread communication refers to the methods and strategies that facilitate the exchange of information and coordination between different threads running concurrently in a Java program. Achieving smooth inter-thread communication is pivotal in ensuring that your multi-threaded programs operate harmoniously, without clashes or collisions that can arise from unsynchronized access to shared resources. The Java programming language offers built-in mechanisms such as <code>wait()</code>, <code>notify()</code>, and <code>notifyAll()</code> methods, which play a vital role in facilitating inter-thread communication, helping to build more robust and efficient programs.</p>



<h3 class="wp-block-heading">4.2 The wait(), notify(), and notifyAll() Methods</h3>



<p>The <code>wait()</code>, <code>notify()</code>, and <code>notifyAll()</code> methods are intrinsic methods in Java that are essential tools for facilitating inter-thread communication. They are part of the <code>Object</code> class, and therefore available in every Java object.</p>



<ul class="wp-block-list">
<li><strong>wait()</strong>: This method is used to make a thread give up the monitor and go to sleep until some other thread enters the same monitor and calls notify( ) or notifyAll( ). It essentially causes the current thread to wait until another thread invokes the <code>notify()</code> method or the <code>notifyAll()</code> method for this object.</li>
</ul>



<div class="wp-block-kevinbatdorf-code-block-pro" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:clamp(14px, .875rem, 21px);font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:clamp(20px, 1.25rem, 30px);--cbp-tab-width:4;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:10px 0px 10px 16px;margin-bottom:-2px;width:100%;text-align:left;background-color:#2f363c;color:#d3d7dd">Java</span><span role="button" tabindex="0" data-code="synchronized (obj) {
    while (&lt;condition does not hold&gt;)
        obj.wait();
    // ...
}" style="color:#e1e4e8;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki github-dark" style="background-color: #24292e" tabindex="0"><code><span class="line"><span style="color: #F97583">synchronized</span><span style="color: #E1E4E8"> (obj) {</span></span>
<span class="line"><span style="color: #E1E4E8">    </span><span style="color: #F97583">while</span><span style="color: #E1E4E8"> (</span><span style="color: #F97583">&lt;</span><span style="color: #E1E4E8">condition does not hold</span><span style="color: #F97583">&gt;</span><span style="color: #E1E4E8">)</span></span>
<span class="line"><span style="color: #E1E4E8">        obj.</span><span style="color: #B392F0">wait</span><span style="color: #E1E4E8">();</span></span>
<span class="line"><span style="color: #E1E4E8">    </span><span style="color: #6A737D">// ...</span></span>
<span class="line"><span style="color: #E1E4E8">}</span></span></code></pre></div>



<ul class="wp-block-list">
<li><strong>notify()</strong>: This method wakes up a single thread that is waiting on this object&#8217;s monitor. If any threads are waiting on this object, one of them is chosen to be awakened.</li>
</ul>



<div class="wp-block-kevinbatdorf-code-block-pro" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:clamp(14px, .875rem, 21px);font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:clamp(20px, 1.25rem, 30px);--cbp-tab-width:4;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:10px 0px 10px 16px;margin-bottom:-2px;width:100%;text-align:left;background-color:#2f363c;color:#d3d7dd">Java</span><span role="button" tabindex="0" data-code="synchronized (obj) {
    obj.notify();
}" style="color:#e1e4e8;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki github-dark" style="background-color: #24292e" tabindex="0"><code><span class="line"><span style="color: #F97583">synchronized</span><span style="color: #E1E4E8"> (obj) {</span></span>
<span class="line"><span style="color: #E1E4E8">    obj.</span><span style="color: #B392F0">notify</span><span style="color: #E1E4E8">();</span></span>
<span class="line"><span style="color: #E1E4E8">}</span></span></code></pre></div>



<ul class="wp-block-list">
<li><strong>notifyAll()</strong>: This method wakes up all threads that are waiting on this object&#8217;s monitor. A thread waits on an object&#8217;s monitor by calling one of the <code>wait</code> methods.</li>
</ul>



<div class="wp-block-kevinbatdorf-code-block-pro" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:clamp(14px, .875rem, 21px);font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:clamp(20px, 1.25rem, 30px);--cbp-tab-width:4;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:10px 0px 10px 16px;margin-bottom:-2px;width:100%;text-align:left;background-color:#2f363c;color:#d3d7dd">Java</span><span role="button" tabindex="0" data-code="synchronized (obj) {
    obj.notifyAll();
}" style="color:#e1e4e8;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki github-dark" style="background-color: #24292e" tabindex="0"><code><span class="line"><span style="color: #F97583">synchronized</span><span style="color: #E1E4E8"> (obj) {</span></span>
<span class="line"><span style="color: #E1E4E8">    obj.</span><span style="color: #B392F0">notifyAll</span><span style="color: #E1E4E8">();</span></span>
<span class="line"><span style="color: #E1E4E8">}</span></span></code></pre></div>



<p>Understanding how to use these methods properly and judiciously can help you create programs with multiple threads that interact and communicate flawlessly, allowing you to implement complex coordination between threads.</p>



<h3 class="wp-block-heading">4.3 Deadlock and How to Avoid It</h3>



<p>A deadlock is a condition in a multi-threading environment where two or more threads cannot proceed because each is waiting for the other to release a lock. In a deadlock situation, the threads remain blocked forever, making part or all of the program non-functional.</p>



<p>Avoiding deadlock involves careful program design to ensure that threads do not end up waiting for each other indefinitely. Here are strategies to avoid deadlock:</p>



<ul class="wp-block-list">
<li><strong>Lock Hierarchies</strong>: Always acquire locks in a predefined order.</li>



<li><strong>Timeouts</strong>: Set timeouts while attempting to acquire a lock, ensuring threads do not wait indefinitely.</li>



<li><strong>Deadlock Detection Algorithms</strong>: Implement algorithms that can detect and recover from deadlocks.</li>
</ul>



<p>Understanding the scenarios that can lead to deadlock and planning your synchronization strategy accordingly is crucial in developing multi-threaded applications that are both robust and deadlock-free.</p>



<h3 class="wp-block-heading">4.4 Producer-Consumer Problem</h3>



<p>The producer-consumer problem, also known as the bounded-buffer problem, is a classic example of a multi-process synchronization problem. The problem describes two processes, the producer and the consumer, who share a common, fixed-size buffer as storage.</p>



<ul class="wp-block-list">
<li><strong>Producer</strong>: The producer&#8217;s job is to generate a piece of data, put it into the buffer, and start again.</li>



<li><strong>Consumer</strong>: On the other side, the consumer is consuming the data (i.e., removing it from the buffer), one piece at a time.</li>
</ul>



<p>To solve this problem, we employ the concept of inter-thread communication to ensure that the producer won’t try to add data into the buffer if it&#8217;s full and that the consumer won’t try to remove data from an empty buffer.</p>



<p>Java provides a variety of solutions, including the <code>wait()</code> and <code>notify()</code> methods discussed above, or higher-level concurrency utilities such as <code>BlockingQueue</code> which can simplify the implementation significantly.</p>



<div class="wp-block-kevinbatdorf-code-block-pro" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:clamp(14px, .875rem, 21px);font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:clamp(20px, 1.25rem, 30px);--cbp-tab-width:4;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:10px 0px 10px 16px;margin-bottom:-2px;width:100%;text-align:left;background-color:#2f363c;color:#d3d7dd">Java</span><span role="button" tabindex="0" data-code="BlockingQueue&lt;Integer&gt; buffer = new ArrayBlockingQueue&lt;&gt;(10);

class Producer implements Runnable {
    public void run() {
        while (true) {
            try {
                buffer.put(produce());
            } catch (InterruptedException ex) {
                Thread.currentThread().interrupt();
            }
        }
    }
    
    private int produce() {
        // ... (produce data)
        return 1;
    }
}

class Consumer implements Runnable {
    public void run() {
        while (true) {
            try {
                consume(buffer.take());
            } catch (InterruptedException ex) {
                Thread.currentThread().interrupt();
            }
        }
    }
    
    private void consume(int data) {
        // ... (consume data)
    }
}" style="color:#e1e4e8;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki github-dark" style="background-color: #24292e" tabindex="0"><code><span class="line"><span style="color: #E1E4E8">BlockingQueue&lt;</span><span style="color: #F97583">Integer</span><span style="color: #E1E4E8">&gt; buffer </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">new</span><span style="color: #E1E4E8"> ArrayBlockingQueue&lt;&gt;(</span><span style="color: #79B8FF">10</span><span style="color: #E1E4E8">);</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F97583">class</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">Producer</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">implements</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">Runnable</span><span style="color: #E1E4E8"> {</span></span>
<span class="line"><span style="color: #E1E4E8">    </span><span style="color: #F97583">public</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">void</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">run</span><span style="color: #E1E4E8">() {</span></span>
<span class="line"><span style="color: #E1E4E8">        </span><span style="color: #F97583">while</span><span style="color: #E1E4E8"> (</span><span style="color: #79B8FF">true</span><span style="color: #E1E4E8">) {</span></span>
<span class="line"><span style="color: #E1E4E8">            </span><span style="color: #F97583">try</span><span style="color: #E1E4E8"> {</span></span>
<span class="line"><span style="color: #E1E4E8">                buffer.</span><span style="color: #B392F0">put</span><span style="color: #E1E4E8">(</span><span style="color: #B392F0">produce</span><span style="color: #E1E4E8">());</span></span>
<span class="line"><span style="color: #E1E4E8">            } </span><span style="color: #F97583">catch</span><span style="color: #E1E4E8"> (InterruptedException </span><span style="color: #FFAB70">ex</span><span style="color: #E1E4E8">) {</span></span>
<span class="line"><span style="color: #E1E4E8">                Thread.</span><span style="color: #B392F0">currentThread</span><span style="color: #E1E4E8">().</span><span style="color: #B392F0">interrupt</span><span style="color: #E1E4E8">();</span></span>
<span class="line"><span style="color: #E1E4E8">            }</span></span>
<span class="line"><span style="color: #E1E4E8">        }</span></span>
<span class="line"><span style="color: #E1E4E8">    }</span></span>
<span class="line"><span style="color: #E1E4E8">    </span></span>
<span class="line"><span style="color: #E1E4E8">    </span><span style="color: #F97583">private</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">int</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">produce</span><span style="color: #E1E4E8">() {</span></span>
<span class="line"><span style="color: #E1E4E8">        </span><span style="color: #6A737D">// ... (produce data)</span></span>
<span class="line"><span style="color: #E1E4E8">        </span><span style="color: #F97583">return</span><span style="color: #E1E4E8"> </span><span style="color: #79B8FF">1</span><span style="color: #E1E4E8">;</span></span>
<span class="line"><span style="color: #E1E4E8">    }</span></span>
<span class="line"><span style="color: #E1E4E8">}</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F97583">class</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">Consumer</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">implements</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">Runnable</span><span style="color: #E1E4E8"> {</span></span>
<span class="line"><span style="color: #E1E4E8">    </span><span style="color: #F97583">public</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">void</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">run</span><span style="color: #E1E4E8">() {</span></span>
<span class="line"><span style="color: #E1E4E8">        </span><span style="color: #F97583">while</span><span style="color: #E1E4E8"> (</span><span style="color: #79B8FF">true</span><span style="color: #E1E4E8">) {</span></span>
<span class="line"><span style="color: #E1E4E8">            </span><span style="color: #F97583">try</span><span style="color: #E1E4E8"> {</span></span>
<span class="line"><span style="color: #E1E4E8">                </span><span style="color: #B392F0">consume</span><span style="color: #E1E4E8">(buffer.</span><span style="color: #B392F0">take</span><span style="color: #E1E4E8">());</span></span>
<span class="line"><span style="color: #E1E4E8">            } </span><span style="color: #F97583">catch</span><span style="color: #E1E4E8"> (InterruptedException </span><span style="color: #FFAB70">ex</span><span style="color: #E1E4E8">) {</span></span>
<span class="line"><span style="color: #E1E4E8">                Thread.</span><span style="color: #B392F0">currentThread</span><span style="color: #E1E4E8">().</span><span style="color: #B392F0">interrupt</span><span style="color: #E1E4E8">();</span></span>
<span class="line"><span style="color: #E1E4E8">            }</span></span>
<span class="line"><span style="color: #E1E4E8">        }</span></span>
<span class="line"><span style="color: #E1E4E8">    }</span></span>
<span class="line"><span style="color: #E1E4E8">    </span></span>
<span class="line"><span style="color: #E1E4E8">    </span><span style="color: #F97583">private</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">void</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">consume</span><span style="color: #E1E4E8">(</span><span style="color: #F97583">int</span><span style="color: #E1E4E8"> </span><span style="color: #FFAB70">data</span><span style="color: #E1E4E8">) {</span></span>
<span class="line"><span style="color: #E1E4E8">        </span><span style="color: #6A737D">// ... (consume data)</span></span>
<span class="line"><span style="color: #E1E4E8">    }</span></span>
<span class="line"><span style="color: #E1E4E8">}</span></span></code></pre></div>



<p>In this solution, a <code>BlockingQueue</code> serves as the buffer, and we have a producer thread and a consumer thread performing their roles concurrently, demonstrating a hands-on solution to the producer-consumer problem.</p>



<h2 class="wp-block-heading">5. The Executors Framework</h2>



<h3 class="wp-block-heading">5.1 Introduction to Executors</h3>



<p>In the realm of Java concurrency, the Executors framework stands as a pivotal system that facilitates the management and control of threads more efficiently compared to manually handling threads through the Thread class. Introduced in Java 5, the Executors framework simplifies the process of task submission and the handling of asynchronous results.</p>



<p>The core of the Executors framework is the Executor interface, supplemented by the <code>ExecutorService</code> and <code>ScheduledExecutorService</code> interfaces, which offer methods to manage and control thread execution precisely. Additionally, the <code>Executors</code> utility class provides a plethora of factory methods to create different types of thread pools, such as a fixed thread pool, a scheduled thread pool, and a cached thread pool.</p>



<p>Before we dive into specific types of thread pools, understanding that a thread pool is a collection of threads where tasks (in the form of <code>Runnable</code> or <code>Callable</code> objects) are submitted to be executed is essential. Utilizing thread pools aids in minimizing the overhead of thread creation and helps in reusing existing threads, thereby enhancing the performance and scalability of the application.</p>



<h3 class="wp-block-heading">5.2 Fixed Thread Pool</h3>



<p>A fixed thread pool is created using the <code>Executors.newFixedThreadPool(int nThreads)</code> method, which generates a thread pool with a fixed number of threads. All threads are available to execute tasks, and if a thread is unavailable, new tasks will wait in a queue until a thread becomes available. Let’s illustrate this with an example:</p>



<div class="wp-block-kevinbatdorf-code-block-pro" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:clamp(14px, .875rem, 21px);font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:clamp(20px, 1.25rem, 30px);--cbp-tab-width:4;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:10px 0px 10px 16px;margin-bottom:-2px;width:100%;text-align:left;background-color:#2f363c;color:#d3d7dd">Java</span><span role="button" tabindex="0" data-code="import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class FixedThreadPoolExample {
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(2);

        for (int i = 0; i &lt; 5; i++) {
            Runnable worker = new WorkerThread(&quot;&quot; + i);
            executorService.execute(worker);
        }

        executorService.shutdown();
        while (!executorService.isTerminated()) {
        }

        System.out.println(&quot;Finished all threads&quot;);
    }

    public static class WorkerThread implements Runnable {
        private String command;

        public WorkerThread(String s) {
            this.command = s;
        }

        public void run() {
            System.out.println(Thread.currentThread().getName() + &quot; Start. Command = &quot; + command);
            processCommand();
            System.out.println(Thread.currentThread().getName() + &quot; End.&quot;);
        }

        private void processCommand() {
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}" style="color:#e1e4e8;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki github-dark" style="background-color: #24292e" tabindex="0"><code><span class="line"><span style="color: #F97583">import</span><span style="color: #E1E4E8"> java.util.concurrent.ExecutorService;</span></span>
<span class="line"><span style="color: #F97583">import</span><span style="color: #E1E4E8"> java.util.concurrent.Executors;</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F97583">public</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">class</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">FixedThreadPoolExample</span><span style="color: #E1E4E8"> {</span></span>
<span class="line"><span style="color: #E1E4E8">    </span><span style="color: #F97583">public</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">static</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">void</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">main</span><span style="color: #E1E4E8">(</span><span style="color: #F97583">String</span><span style="color: #E1E4E8">[] </span><span style="color: #FFAB70">args</span><span style="color: #E1E4E8">) {</span></span>
<span class="line"><span style="color: #E1E4E8">        ExecutorService executorService </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> Executors.</span><span style="color: #B392F0">newFixedThreadPool</span><span style="color: #E1E4E8">(</span><span style="color: #79B8FF">2</span><span style="color: #E1E4E8">);</span></span>
<span class="line"></span>
<span class="line"><span style="color: #E1E4E8">        </span><span style="color: #F97583">for</span><span style="color: #E1E4E8"> (</span><span style="color: #F97583">int</span><span style="color: #E1E4E8"> i </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> </span><span style="color: #79B8FF">0</span><span style="color: #E1E4E8">; i </span><span style="color: #F97583">&lt;</span><span style="color: #E1E4E8"> </span><span style="color: #79B8FF">5</span><span style="color: #E1E4E8">; i</span><span style="color: #F97583">++</span><span style="color: #E1E4E8">) {</span></span>
<span class="line"><span style="color: #E1E4E8">            Runnable worker </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">new</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">WorkerThread</span><span style="color: #E1E4E8">(</span><span style="color: #9ECBFF">&quot;&quot;</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">+</span><span style="color: #E1E4E8"> i);</span></span>
<span class="line"><span style="color: #E1E4E8">            executorService.</span><span style="color: #B392F0">execute</span><span style="color: #E1E4E8">(worker);</span></span>
<span class="line"><span style="color: #E1E4E8">        }</span></span>
<span class="line"></span>
<span class="line"><span style="color: #E1E4E8">        executorService.</span><span style="color: #B392F0">shutdown</span><span style="color: #E1E4E8">();</span></span>
<span class="line"><span style="color: #E1E4E8">        </span><span style="color: #F97583">while</span><span style="color: #E1E4E8"> (</span><span style="color: #F97583">!</span><span style="color: #E1E4E8">executorService.</span><span style="color: #B392F0">isTerminated</span><span style="color: #E1E4E8">()) {</span></span>
<span class="line"><span style="color: #E1E4E8">        }</span></span>
<span class="line"></span>
<span class="line"><span style="color: #E1E4E8">        System.out.</span><span style="color: #B392F0">println</span><span style="color: #E1E4E8">(</span><span style="color: #9ECBFF">&quot;Finished all threads&quot;</span><span style="color: #E1E4E8">);</span></span>
<span class="line"><span style="color: #E1E4E8">    }</span></span>
<span class="line"></span>
<span class="line"><span style="color: #E1E4E8">    </span><span style="color: #F97583">public</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">static</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">class</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">WorkerThread</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">implements</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">Runnable</span><span style="color: #E1E4E8"> {</span></span>
<span class="line"><span style="color: #E1E4E8">        </span><span style="color: #F97583">private</span><span style="color: #E1E4E8"> String command;</span></span>
<span class="line"></span>
<span class="line"><span style="color: #E1E4E8">        </span><span style="color: #F97583">public</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">WorkerThread</span><span style="color: #E1E4E8">(String </span><span style="color: #FFAB70">s</span><span style="color: #E1E4E8">) {</span></span>
<span class="line"><span style="color: #E1E4E8">            </span><span style="color: #79B8FF">this</span><span style="color: #E1E4E8">.command </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> s;</span></span>
<span class="line"><span style="color: #E1E4E8">        }</span></span>
<span class="line"></span>
<span class="line"><span style="color: #E1E4E8">        </span><span style="color: #F97583">public</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">void</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">run</span><span style="color: #E1E4E8">() {</span></span>
<span class="line"><span style="color: #E1E4E8">            System.out.</span><span style="color: #B392F0">println</span><span style="color: #E1E4E8">(Thread.</span><span style="color: #B392F0">currentThread</span><span style="color: #E1E4E8">().</span><span style="color: #B392F0">getName</span><span style="color: #E1E4E8">() </span><span style="color: #F97583">+</span><span style="color: #E1E4E8"> </span><span style="color: #9ECBFF">&quot; Start. Command = &quot;</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">+</span><span style="color: #E1E4E8"> command);</span></span>
<span class="line"><span style="color: #E1E4E8">            </span><span style="color: #B392F0">processCommand</span><span style="color: #E1E4E8">();</span></span>
<span class="line"><span style="color: #E1E4E8">            System.out.</span><span style="color: #B392F0">println</span><span style="color: #E1E4E8">(Thread.</span><span style="color: #B392F0">currentThread</span><span style="color: #E1E4E8">().</span><span style="color: #B392F0">getName</span><span style="color: #E1E4E8">() </span><span style="color: #F97583">+</span><span style="color: #E1E4E8"> </span><span style="color: #9ECBFF">&quot; End.&quot;</span><span style="color: #E1E4E8">);</span></span>
<span class="line"><span style="color: #E1E4E8">        }</span></span>
<span class="line"></span>
<span class="line"><span style="color: #E1E4E8">        </span><span style="color: #F97583">private</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">void</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">processCommand</span><span style="color: #E1E4E8">() {</span></span>
<span class="line"><span style="color: #E1E4E8">            </span><span style="color: #F97583">try</span><span style="color: #E1E4E8"> {</span></span>
<span class="line"><span style="color: #E1E4E8">                Thread.</span><span style="color: #B392F0">sleep</span><span style="color: #E1E4E8">(</span><span style="color: #79B8FF">5000</span><span style="color: #E1E4E8">);</span></span>
<span class="line"><span style="color: #E1E4E8">            } </span><span style="color: #F97583">catch</span><span style="color: #E1E4E8"> (InterruptedException </span><span style="color: #FFAB70">e</span><span style="color: #E1E4E8">) {</span></span>
<span class="line"><span style="color: #E1E4E8">                e.</span><span style="color: #B392F0">printStackTrace</span><span style="color: #E1E4E8">();</span></span>
<span class="line"><span style="color: #E1E4E8">            }</span></span>
<span class="line"><span style="color: #E1E4E8">        }</span></span>
<span class="line"><span style="color: #E1E4E8">    }</span></span>
<span class="line"><span style="color: #E1E4E8">}</span></span></code></pre></div>



<p>In this example, a fixed thread pool with 2 threads is created. Five tasks are submitted, but only two tasks can run in parallel. Other tasks will be waiting in a queue.</p>



<h3 class="wp-block-heading">5.3 Scheduled Thread Pool</h3>



<p>A scheduled thread pool is utilized to schedule tasks to be executed after a predefined delay or to execute periodically. It can be created using <code>Executors.newScheduledThreadPool(int corePoolSize)</code>. Let&#8217;s delve into an illustrative example:</p>



<div class="wp-block-kevinbatdorf-code-block-pro" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:clamp(14px, .875rem, 21px);font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:clamp(20px, 1.25rem, 30px);--cbp-tab-width:4;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:10px 0px 10px 16px;margin-bottom:-2px;width:100%;text-align:left;background-color:#2f363c;color:#d3d7dd">Java</span><span role="button" tabindex="0" data-code="import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class ScheduledThreadPoolExample {
    public static void main(String[] args) {
        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);

        Runnable task = () -&gt; {
            System.out.println(&quot;Executing Task At &quot; + System.nanoTime());
        };

        scheduledExecutorService.scheduleAtFixedRate(task, 0, 2, TimeUnit.SECONDS);
    }
}" style="color:#e1e4e8;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki github-dark" style="background-color: #24292e" tabindex="0"><code><span class="line"><span style="color: #F97583">import</span><span style="color: #E1E4E8"> java.util.concurrent.Executors;</span></span>
<span class="line"><span style="color: #F97583">import</span><span style="color: #E1E4E8"> java.util.concurrent.ScheduledExecutorService;</span></span>
<span class="line"><span style="color: #F97583">import</span><span style="color: #E1E4E8"> java.util.concurrent.TimeUnit;</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F97583">public</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">class</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">ScheduledThreadPoolExample</span><span style="color: #E1E4E8"> {</span></span>
<span class="line"><span style="color: #E1E4E8">    </span><span style="color: #F97583">public</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">static</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">void</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">main</span><span style="color: #E1E4E8">(</span><span style="color: #F97583">String</span><span style="color: #E1E4E8">[] </span><span style="color: #FFAB70">args</span><span style="color: #E1E4E8">) {</span></span>
<span class="line"><span style="color: #E1E4E8">        ScheduledExecutorService scheduledExecutorService </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> Executors.</span><span style="color: #B392F0">newScheduledThreadPool</span><span style="color: #E1E4E8">(</span><span style="color: #79B8FF">1</span><span style="color: #E1E4E8">);</span></span>
<span class="line"></span>
<span class="line"><span style="color: #E1E4E8">        Runnable task </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> () </span><span style="color: #F97583">-&gt;</span><span style="color: #E1E4E8"> {</span></span>
<span class="line"><span style="color: #E1E4E8">            System.out.</span><span style="color: #B392F0">println</span><span style="color: #E1E4E8">(</span><span style="color: #9ECBFF">&quot;Executing Task At &quot;</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">+</span><span style="color: #E1E4E8"> System.</span><span style="color: #B392F0">nanoTime</span><span style="color: #E1E4E8">());</span></span>
<span class="line"><span style="color: #E1E4E8">        };</span></span>
<span class="line"></span>
<span class="line"><span style="color: #E1E4E8">        scheduledExecutorService.</span><span style="color: #B392F0">scheduleAtFixedRate</span><span style="color: #E1E4E8">(task, </span><span style="color: #79B8FF">0</span><span style="color: #E1E4E8">, </span><span style="color: #79B8FF">2</span><span style="color: #E1E4E8">, TimeUnit.SECONDS);</span></span>
<span class="line"><span style="color: #E1E4E8">    }</span></span>
<span class="line"><span style="color: #E1E4E8">}</span></span></code></pre></div>



<p>n this example, a scheduled thread pool with one thread is created. The task is scheduled to execute at a fixed rate of every 2 seconds, showcasing the utility of scheduled thread pools in executing tasks periodically.</p>



<h3 class="wp-block-heading">5.4 Cached Thread Pool</h3>



<p>The cached thread pool is an unbounded pool which automatically creates new threads as needed, and reuses previously constructed threads available. It is created using <code>Executors.newCachedThreadPool()</code>. Threads that have not been used for sixty seconds are terminated and removed from the cache. Here is a simple demonstration:</p>



<div class="wp-block-kevinbatdorf-code-block-pro" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:clamp(14px, .875rem, 21px);font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:clamp(20px, 1.25rem, 30px);--cbp-tab-width:4;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:10px 0px 10px 16px;margin-bottom:-2px;width:100%;text-align:left;background-color:#2f363c;color:#d3d7dd">Java</span><span role="button" tabindex="0" data-code="import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class CachedThreadPoolExample {
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newCachedThreadPool();

        for (int i = 0; i &lt; 5; i++) {
            Runnable worker = new WorkerThread(&quot;&quot; + i);
            executorService.execute(worker);
        }

        executorService.shutdown();
    }

    public static class WorkerThread implements Runnable {
        private String command;

        public WorkerThread(String s) {
            this.command = s;
        }

        public void run() {
            System.out.println(Thread.currentThread().getName() + &quot; Start. Command = &quot; + command);
            processCommand();
            System.out.println(Thread.currentThread().getName() + &quot; End.&quot;);
        }

        private void processCommand() {
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}" style="color:#e1e4e8;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki github-dark" style="background-color: #24292e" tabindex="0"><code><span class="line"><span style="color: #F97583">import</span><span style="color: #E1E4E8"> java.util.concurrent.ExecutorService;</span></span>
<span class="line"><span style="color: #F97583">import</span><span style="color: #E1E4E8"> java.util.concurrent.Executors;</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F97583">public</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">class</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">CachedThreadPoolExample</span><span style="color: #E1E4E8"> {</span></span>
<span class="line"><span style="color: #E1E4E8">    </span><span style="color: #F97583">public</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">static</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">void</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">main</span><span style="color: #E1E4E8">(</span><span style="color: #F97583">String</span><span style="color: #E1E4E8">[] </span><span style="color: #FFAB70">args</span><span style="color: #E1E4E8">) {</span></span>
<span class="line"><span style="color: #E1E4E8">        ExecutorService executorService </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> Executors.</span><span style="color: #B392F0">newCachedThreadPool</span><span style="color: #E1E4E8">();</span></span>
<span class="line"></span>
<span class="line"><span style="color: #E1E4E8">        </span><span style="color: #F97583">for</span><span style="color: #E1E4E8"> (</span><span style="color: #F97583">int</span><span style="color: #E1E4E8"> i </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> </span><span style="color: #79B8FF">0</span><span style="color: #E1E4E8">; i </span><span style="color: #F97583">&lt;</span><span style="color: #E1E4E8"> </span><span style="color: #79B8FF">5</span><span style="color: #E1E4E8">; i</span><span style="color: #F97583">++</span><span style="color: #E1E4E8">) {</span></span>
<span class="line"><span style="color: #E1E4E8">            Runnable worker </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">new</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">WorkerThread</span><span style="color: #E1E4E8">(</span><span style="color: #9ECBFF">&quot;&quot;</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">+</span><span style="color: #E1E4E8"> i);</span></span>
<span class="line"><span style="color: #E1E4E8">            executorService.</span><span style="color: #B392F0">execute</span><span style="color: #E1E4E8">(worker);</span></span>
<span class="line"><span style="color: #E1E4E8">        }</span></span>
<span class="line"></span>
<span class="line"><span style="color: #E1E4E8">        executorService.</span><span style="color: #B392F0">shutdown</span><span style="color: #E1E4E8">();</span></span>
<span class="line"><span style="color: #E1E4E8">    }</span></span>
<span class="line"></span>
<span class="line"><span style="color: #E1E4E8">    </span><span style="color: #F97583">public</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">static</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">class</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">WorkerThread</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">implements</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">Runnable</span><span style="color: #E1E4E8"> {</span></span>
<span class="line"><span style="color: #E1E4E8">        </span><span style="color: #F97583">private</span><span style="color: #E1E4E8"> String command;</span></span>
<span class="line"></span>
<span class="line"><span style="color: #E1E4E8">        </span><span style="color: #F97583">public</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">WorkerThread</span><span style="color: #E1E4E8">(String </span><span style="color: #FFAB70">s</span><span style="color: #E1E4E8">) {</span></span>
<span class="line"><span style="color: #E1E4E8">            </span><span style="color: #79B8FF">this</span><span style="color: #E1E4E8">.command </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> s;</span></span>
<span class="line"><span style="color: #E1E4E8">        }</span></span>
<span class="line"></span>
<span class="line"><span style="color: #E1E4E8">        </span><span style="color: #F97583">public</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">void</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">run</span><span style="color: #E1E4E8">() {</span></span>
<span class="line"><span style="color: #E1E4E8">            System.out.</span><span style="color: #B392F0">println</span><span style="color: #E1E4E8">(Thread.</span><span style="color: #B392F0">currentThread</span><span style="color: #E1E4E8">().</span><span style="color: #B392F0">getName</span><span style="color: #E1E4E8">() </span><span style="color: #F97583">+</span><span style="color: #E1E4E8"> </span><span style="color: #9ECBFF">&quot; Start. Command = &quot;</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">+</span><span style="color: #E1E4E8"> command);</span></span>
<span class="line"><span style="color: #E1E4E8">            </span><span style="color: #B392F0">processCommand</span><span style="color: #E1E4E8">();</span></span>
<span class="line"><span style="color: #E1E4E8">            System.out.</span><span style="color: #B392F0">println</span><span style="color: #E1E4E8">(Thread.</span><span style="color: #B392F0">currentThread</span><span style="color: #E1E4E8">().</span><span style="color: #B392F0">getName</span><span style="color: #E1E4E8">() </span><span style="color: #F97583">+</span><span style="color: #E1E4E8"> </span><span style="color: #9ECBFF">&quot; End.&quot;</span><span style="color: #E1E4E8">);</span></span>
<span class="line"><span style="color: #E1E4E8">        }</span></span>
<span class="line"></span>
<span class="line"><span style="color: #E1E4E8">        </span><span style="color: #F97583">private</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">void</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">processCommand</span><span style="color: #E1E4E8">() {</span></span>
<span class="line"><span style="color: #E1E4E8">            </span><span style="color: #F97583">try</span><span style="color: #E1E4E8"> {</span></span>
<span class="line"><span style="color: #E1E4E8">                Thread.</span><span style="color: #B392F0">sleep</span><span style="color: #E1E4E8">(</span><span style="color: #79B8FF">5000</span><span style="color: #E1E4E8">);</span></span>
<span class="line"><span style="color: #E1E4E8">            } </span><span style="color: #F97583">catch</span><span style="color: #E1E4E8"> (InterruptedException </span><span style="color: #FFAB70">e</span><span style="color: #E1E4E8">) {</span></span>
<span class="line"><span style="color: #E1E4E8">                e.</span><span style="color: #B392F0">printStackTrace</span><span style="color: #E1E4E8">();</span></span>
<span class="line"><span style="color: #E1E4E8">            }</span></span>
<span class="line"><span style="color: #E1E4E8">        }</span></span>
<span class="line"><span style="color: #E1E4E8">    }</span></span>
<span class="line"><span style="color: #E1E4E8">}</span></span></code></pre></div>



<p>In this code, a cached thread pool is created, which potentially allows the five tasks to run concurrently. This type of thread pool is useful in applications with many short-lived tasks.</p>



<p>Understanding the Executors framework and how to employ different types of thread pools is a cornerstone in mastering Java concurrency, offering a higher level of control and optimization in handling multi-threaded environments efficiently and robustly. It empowers developers to write maintainable, scalable, and optimized concurrent applications in Java.</p>



<h2 class="wp-block-heading">6. Concurrent Collections</h2>



<h3 class="wp-block-heading">6.1 Overview of Concurrent Collections</h3>



<p>Concurrent collections, a subset of the Java Collections Framework, are designed to support concurrent access by multiple threads, efficiently handling the necessary synchronization internally. Introduced as a part of the <code>java.util.concurrent</code> package, concurrent collections include various thread-safe collection classes, which offer high performance while ensuring thread safety during concurrent access and modifications. Before we dive deep into the specific implementations like <code>ConcurrentHashMap</code>, <code>ConcurrentSkipListMap</code>, and <code>ConcurrentLinkedQueue</code>, it is crucial to understand that these classes stand as better alternatives to Collections.synchronizedXXX methods and synchronized blocks as they provide better scalability and performance by leveraging lock stripping and other advanced concurrent programming concepts.</p>



<h3 class="wp-block-heading">6.2 Concurrent HashMap</h3>



<p><code>ConcurrentHashMap</code> is a part of Java&#8217;s concurrent package and it serves as a thread-safe implementation of <code>HashMap</code>. This class allows concurrent access and updates to the map, making it highly efficient in multi-thread environments. Here’s how <code>ConcurrentHashMap</code> is structured and utilized:</p>



<div class="wp-block-kevinbatdorf-code-block-pro" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:clamp(14px, .875rem, 21px);font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:clamp(20px, 1.25rem, 30px);--cbp-tab-width:4;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:10px 0px 10px 16px;margin-bottom:-2px;width:100%;text-align:left;background-color:#2f363c;color:#d3d7dd">Java</span><span role="button" tabindex="0" data-code="import java.util.concurrent.ConcurrentHashMap;

public class ConcurrentHashMapExample {
    public static void main(String[] args) {
        ConcurrentHashMap&lt;String, Integer&gt; concurrentHashMap = new ConcurrentHashMap&lt;&gt;();
        concurrentHashMap.put(&quot;A&quot;, 1);
        concurrentHashMap.put(&quot;B&quot;, 2);
        
        concurrentHashMap.forEach((k, v) -&gt; System.out.println(k + &quot;: &quot; + v));
    }
}" style="color:#e1e4e8;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki github-dark" style="background-color: #24292e" tabindex="0"><code><span class="line"><span style="color: #F97583">import</span><span style="color: #E1E4E8"> java.util.concurrent.ConcurrentHashMap;</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F97583">public</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">class</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">ConcurrentHashMapExample</span><span style="color: #E1E4E8"> {</span></span>
<span class="line"><span style="color: #E1E4E8">    </span><span style="color: #F97583">public</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">static</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">void</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">main</span><span style="color: #E1E4E8">(</span><span style="color: #F97583">String</span><span style="color: #E1E4E8">[] </span><span style="color: #FFAB70">args</span><span style="color: #E1E4E8">) {</span></span>
<span class="line"><span style="color: #E1E4E8">        ConcurrentHashMap&lt;</span><span style="color: #F97583">String</span><span style="color: #E1E4E8">, </span><span style="color: #F97583">Integer</span><span style="color: #E1E4E8">&gt; concurrentHashMap </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">new</span><span style="color: #E1E4E8"> ConcurrentHashMap&lt;&gt;();</span></span>
<span class="line"><span style="color: #E1E4E8">        concurrentHashMap.</span><span style="color: #B392F0">put</span><span style="color: #E1E4E8">(</span><span style="color: #9ECBFF">&quot;A&quot;</span><span style="color: #E1E4E8">, </span><span style="color: #79B8FF">1</span><span style="color: #E1E4E8">);</span></span>
<span class="line"><span style="color: #E1E4E8">        concurrentHashMap.</span><span style="color: #B392F0">put</span><span style="color: #E1E4E8">(</span><span style="color: #9ECBFF">&quot;B&quot;</span><span style="color: #E1E4E8">, </span><span style="color: #79B8FF">2</span><span style="color: #E1E4E8">);</span></span>
<span class="line"><span style="color: #E1E4E8">        </span></span>
<span class="line"><span style="color: #E1E4E8">        concurrentHashMap.</span><span style="color: #B392F0">forEach</span><span style="color: #E1E4E8">((k, v) </span><span style="color: #F97583">-&gt;</span><span style="color: #E1E4E8"> System.out.</span><span style="color: #B392F0">println</span><span style="color: #E1E4E8">(k </span><span style="color: #F97583">+</span><span style="color: #E1E4E8"> </span><span style="color: #9ECBFF">&quot;: &quot;</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">+</span><span style="color: #E1E4E8"> v));</span></span>
<span class="line"><span style="color: #E1E4E8">    }</span></span>
<span class="line"><span style="color: #E1E4E8">}</span></span></code></pre></div>



<p>In this example, a <code>ConcurrentHashMap</code> instance is created and populated with key-value pairs. The <code>forEach</code> method is then used to iterate over the map entries concurrently, exhibiting the thread-safe nature of <code>ConcurrentHashMap</code>. It internally manages locks at segment level, thus allowing a higher degree of concurrency as compared to synchronized blocks or collections.</p>



<h3 class="wp-block-heading">6.3 Concurrent Skip List Map</h3>



<p>The <code>ConcurrentSkipListMap</code> is a scalable concurrent <code>NavigableMap</code> implementation based on a skip list. Skip lists are a probabilistic data structure that provides expected logarithmic time complexity for most operations, while ensuring thread-safety. Here is how we can use <code>ConcurrentSkipListMap</code>:</p>



<div class="wp-block-kevinbatdorf-code-block-pro" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:clamp(14px, .875rem, 21px);font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:clamp(20px, 1.25rem, 30px);--cbp-tab-width:4;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:10px 0px 10px 16px;margin-bottom:-2px;width:100%;text-align:left;background-color:#2f363c;color:#d3d7dd">Java</span><span role="button" tabindex="0" data-code="import java.util.concurrent.ConcurrentSkipListMap;

public class ConcurrentSkipListMapExample {
    public static void main(String[] args) {
        ConcurrentSkipListMap&lt;String, Integer&gt; skipListMap = new ConcurrentSkipListMap&lt;&gt;();
        skipListMap.put(&quot;X&quot;, 500);
        skipListMap.put(&quot;Y&quot;, 200);
        skipListMap.put(&quot;Z&quot;, 300);
        
        skipListMap.entrySet().stream().forEach(e -&gt; System.out.println(e.getKey() + &quot;: &quot; + e.getValue()));
    }
}" style="color:#e1e4e8;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki github-dark" style="background-color: #24292e" tabindex="0"><code><span class="line"><span style="color: #F97583">import</span><span style="color: #E1E4E8"> java.util.concurrent.ConcurrentSkipListMap;</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F97583">public</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">class</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">ConcurrentSkipListMapExample</span><span style="color: #E1E4E8"> {</span></span>
<span class="line"><span style="color: #E1E4E8">    </span><span style="color: #F97583">public</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">static</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">void</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">main</span><span style="color: #E1E4E8">(</span><span style="color: #F97583">String</span><span style="color: #E1E4E8">[] </span><span style="color: #FFAB70">args</span><span style="color: #E1E4E8">) {</span></span>
<span class="line"><span style="color: #E1E4E8">        ConcurrentSkipListMap&lt;</span><span style="color: #F97583">String</span><span style="color: #E1E4E8">, </span><span style="color: #F97583">Integer</span><span style="color: #E1E4E8">&gt; skipListMap </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">new</span><span style="color: #E1E4E8"> ConcurrentSkipListMap&lt;&gt;();</span></span>
<span class="line"><span style="color: #E1E4E8">        skipListMap.</span><span style="color: #B392F0">put</span><span style="color: #E1E4E8">(</span><span style="color: #9ECBFF">&quot;X&quot;</span><span style="color: #E1E4E8">, </span><span style="color: #79B8FF">500</span><span style="color: #E1E4E8">);</span></span>
<span class="line"><span style="color: #E1E4E8">        skipListMap.</span><span style="color: #B392F0">put</span><span style="color: #E1E4E8">(</span><span style="color: #9ECBFF">&quot;Y&quot;</span><span style="color: #E1E4E8">, </span><span style="color: #79B8FF">200</span><span style="color: #E1E4E8">);</span></span>
<span class="line"><span style="color: #E1E4E8">        skipListMap.</span><span style="color: #B392F0">put</span><span style="color: #E1E4E8">(</span><span style="color: #9ECBFF">&quot;Z&quot;</span><span style="color: #E1E4E8">, </span><span style="color: #79B8FF">300</span><span style="color: #E1E4E8">);</span></span>
<span class="line"><span style="color: #E1E4E8">        </span></span>
<span class="line"><span style="color: #E1E4E8">        skipListMap.</span><span style="color: #B392F0">entrySet</span><span style="color: #E1E4E8">().</span><span style="color: #B392F0">stream</span><span style="color: #E1E4E8">().</span><span style="color: #B392F0">forEach</span><span style="color: #E1E4E8">(e </span><span style="color: #F97583">-&gt;</span><span style="color: #E1E4E8"> System.out.</span><span style="color: #B392F0">println</span><span style="color: #E1E4E8">(e.</span><span style="color: #B392F0">getKey</span><span style="color: #E1E4E8">() </span><span style="color: #F97583">+</span><span style="color: #E1E4E8"> </span><span style="color: #9ECBFF">&quot;: &quot;</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">+</span><span style="color: #E1E4E8"> e.</span><span style="color: #B392F0">getValue</span><span style="color: #E1E4E8">()));</span></span>
<span class="line"><span style="color: #E1E4E8">    }</span></span>
<span class="line"><span style="color: #E1E4E8">}</span></span></code></pre></div>



<p>In this code snippet, a <code>ConcurrentSkipListMap</code> instance is created, populated with key-value pairs, and iterated over using a stream and a forEach method to demonstrate its utility in concurrent environments. It maintains its elements in a sorted order, which is advantageous in scenarios requiring sorted data structures.</p>



<h3 class="wp-block-heading">6.4 Concurrent Linked Queue</h3>



<p>Finally, we have the <code>ConcurrentLinkedQueue</code>, a high-performance, unbounded, thread-safe queue based on linked nodes. This queue orders elements in a FIFO (first-in-first-out) manner. Let’s look at how to implement this:</p>



<div class="wp-block-kevinbatdorf-code-block-pro" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:clamp(14px, .875rem, 21px);font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:clamp(20px, 1.25rem, 30px);--cbp-tab-width:4;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:10px 0px 10px 16px;margin-bottom:-2px;width:100%;text-align:left;background-color:#2f363c;color:#d3d7dd">Java</span><span role="button" tabindex="0" data-code="import java.util.concurrent.ConcurrentLinkedQueue;

public class ConcurrentLinkedQueueExample {
    public static void main(String[] args) {
        ConcurrentLinkedQueue&lt;String&gt; queue = new ConcurrentLinkedQueue&lt;&gt;();
        queue.add(&quot;element1&quot;);
        queue.add(&quot;element2&quot;);
        
        queue.forEach(element -&gt; System.out.println(element));
    }
}" style="color:#e1e4e8;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki github-dark" style="background-color: #24292e" tabindex="0"><code><span class="line"><span style="color: #F97583">import</span><span style="color: #E1E4E8"> java.util.concurrent.ConcurrentLinkedQueue;</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F97583">public</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">class</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">ConcurrentLinkedQueueExample</span><span style="color: #E1E4E8"> {</span></span>
<span class="line"><span style="color: #E1E4E8">    </span><span style="color: #F97583">public</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">static</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">void</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">main</span><span style="color: #E1E4E8">(</span><span style="color: #F97583">String</span><span style="color: #E1E4E8">[] </span><span style="color: #FFAB70">args</span><span style="color: #E1E4E8">) {</span></span>
<span class="line"><span style="color: #E1E4E8">        ConcurrentLinkedQueue&lt;</span><span style="color: #F97583">String</span><span style="color: #E1E4E8">&gt; queue </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">new</span><span style="color: #E1E4E8"> ConcurrentLinkedQueue&lt;&gt;();</span></span>
<span class="line"><span style="color: #E1E4E8">        queue.</span><span style="color: #B392F0">add</span><span style="color: #E1E4E8">(</span><span style="color: #9ECBFF">&quot;element1&quot;</span><span style="color: #E1E4E8">);</span></span>
<span class="line"><span style="color: #E1E4E8">        queue.</span><span style="color: #B392F0">add</span><span style="color: #E1E4E8">(</span><span style="color: #9ECBFF">&quot;element2&quot;</span><span style="color: #E1E4E8">);</span></span>
<span class="line"><span style="color: #E1E4E8">        </span></span>
<span class="line"><span style="color: #E1E4E8">        queue.</span><span style="color: #B392F0">forEach</span><span style="color: #E1E4E8">(element </span><span style="color: #F97583">-&gt;</span><span style="color: #E1E4E8"> System.out.</span><span style="color: #B392F0">println</span><span style="color: #E1E4E8">(element));</span></span>
<span class="line"><span style="color: #E1E4E8">    }</span></span>
<span class="line"><span style="color: #E1E4E8">}</span></span></code></pre></div>



<p>In the above example, a <code>ConcurrentLinkedQueue</code> instance is created and populated with elements, followed by a forEach iteration over its elements, showcasing the queue’s concurrent nature and how it maintains the order of insertion.</p>



<p>Diving deep into concurrent collections and their specific implementations arms developers with the capability to write highly concurrent applications with optimized data structures that can safely and efficiently operate in a multithreaded environment, thereby enhancing the application&#8217;s performance and scalability.</p>



<p><em>Article continues in <a href="https://blog.j-dev.app/java-guide-to-concurrency-and-multithreading/2/#7_Locks_in_Java" data-type="page" data-id="207">next page</a>.</em></p>


]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Java Generics Explained: Your Route to Robust Java Applications</title>
		<link>https://blog.j-dev.app/java-generics-explained/</link>
		
		<dc:creator><![CDATA[JuanC]]></dc:creator>
		<pubDate>Mon, 18 Sep 2023 21:09:05 +0000</pubDate>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Generics]]></category>
		<guid isPermaLink="false">https://blog.j-dev.app/?page_id=195</guid>

					<description><![CDATA[In the dynamic landscape of software development, Java continues to stand as a robust pillar, constantly evolving to offer features that streamline programming and enhance code reusability and type safety. One of such features is Generics, introduced in Java 5. Generics enable types (classes and interfaces) to be parameters when defining classes, interfaces, and methods. [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p>In the dynamic landscape of software development, Java continues to stand as a robust pillar, constantly evolving to offer features that streamline programming and enhance code reusability and type safety. One of such features is Generics, introduced in Java 5. Generics enable types (classes and interfaces) to be parameters when defining classes, interfaces, and methods. In this article, we explore the world of Generics, from its fundamentals to sophisticated applications, to foster a comprehensive understanding for developers of all levels.</p>



<h2 class="wp-block-heading"><strong>Getting Acquainted with Generics</strong></h2>



<h3 class="wp-block-heading"><strong>Understanding the Concept</strong></h3>



<p>Generics provide a way for you to define classes, interfaces, and methods with a placeholder for the type of data that they will be operating on. The major advantage of Generics is the stronger type checks at compile time, which makes the code more stable and efficient.</p>



<h3 class="wp-block-heading"><strong>The Basics: Generic Classes and Methods</strong></h3>



<p>Before diving deeper, let&#8217;s get familiarized with how to define a generic class and methods:</p>



<div class="wp-block-kevinbatdorf-code-block-pro" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:clamp(14px, .875rem, 21px);font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:clamp(20px, 1.25rem, 30px);--cbp-tab-width:4;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:10px 0px 10px 16px;margin-bottom:-2px;width:100%;text-align:left;background-color:#2f363c;color:#d3d7dd">Java</span><span role="button" tabindex="0" data-code="public class Box&lt;T&gt; {
    private T t;

    public void set(T t) {
        this.t = t;
    }

    public T get() {
        return t;
    }
}

public class GenericMethod {
    public static &lt;E&gt; void printArray(E[] inputArray) {
        for (E element : inputArray) {
            System.out.printf(&quot;%s &quot;, element);
        }
    }
}" style="color:#e1e4e8;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki github-dark" style="background-color: #24292e" tabindex="0"><code><span class="line"><span style="color: #F97583">public</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">class</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">Box</span><span style="color: #E1E4E8">&lt;</span><span style="color: #F97583">T</span><span style="color: #E1E4E8">&gt; {</span></span>
<span class="line"><span style="color: #E1E4E8">    </span><span style="color: #F97583">private</span><span style="color: #E1E4E8"> T t;</span></span>
<span class="line"></span>
<span class="line"><span style="color: #E1E4E8">    </span><span style="color: #F97583">public</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">void</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">set</span><span style="color: #E1E4E8">(T </span><span style="color: #FFAB70">t</span><span style="color: #E1E4E8">) {</span></span>
<span class="line"><span style="color: #E1E4E8">        </span><span style="color: #79B8FF">this</span><span style="color: #E1E4E8">.t </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> t;</span></span>
<span class="line"><span style="color: #E1E4E8">    }</span></span>
<span class="line"></span>
<span class="line"><span style="color: #E1E4E8">    </span><span style="color: #F97583">public</span><span style="color: #E1E4E8"> T </span><span style="color: #B392F0">get</span><span style="color: #E1E4E8">() {</span></span>
<span class="line"><span style="color: #E1E4E8">        </span><span style="color: #F97583">return</span><span style="color: #E1E4E8"> t;</span></span>
<span class="line"><span style="color: #E1E4E8">    }</span></span>
<span class="line"><span style="color: #E1E4E8">}</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F97583">public</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">class</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">GenericMethod</span><span style="color: #E1E4E8"> {</span></span>
<span class="line"><span style="color: #E1E4E8">    </span><span style="color: #F97583">public</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">static</span><span style="color: #E1E4E8"> &lt;</span><span style="color: #F97583">E</span><span style="color: #E1E4E8">&gt; </span><span style="color: #F97583">void</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">printArray</span><span style="color: #E1E4E8">(</span><span style="color: #F97583">E</span><span style="color: #E1E4E8">[] </span><span style="color: #FFAB70">inputArray</span><span style="color: #E1E4E8">) {</span></span>
<span class="line"><span style="color: #E1E4E8">        </span><span style="color: #F97583">for</span><span style="color: #E1E4E8"> (E element </span><span style="color: #F97583">:</span><span style="color: #E1E4E8"> inputArray) {</span></span>
<span class="line"><span style="color: #E1E4E8">            System.out.</span><span style="color: #B392F0">printf</span><span style="color: #E1E4E8">(</span><span style="color: #9ECBFF">&quot;%s &quot;</span><span style="color: #E1E4E8">, element);</span></span>
<span class="line"><span style="color: #E1E4E8">        }</span></span>
<span class="line"><span style="color: #E1E4E8">    }</span></span>
<span class="line"><span style="color: #E1E4E8">}</span></span></code></pre></div>



<p>In the above example, <code>T</code> and <code>E</code> are type parameters, standing in for the actual types that will be used when creating instances of <code>Box</code> and when calling <code>printArray</code>, respectively.</p>



<h2 class="wp-block-heading"><strong>Exploring Deeper into Generics</strong></h2>



<p>After understanding the foundational concepts of generics and familiarizing oneself with the basics of generic classes and methods, it is crucial to explore deeper into the underpinning principles that govern generics in Java, aiming to comprehend why this feature is not just useful but indeed indispensable in crafting robust and maintainable Java applications. In this segment, we will elaborate further on the concept of generics, the rationale behind its inception, and the multiple advantages it brings to the table in software development.</p>



<h3 class="wp-block-heading"><strong>The Essence of Generics</strong></h3>



<p>Generics, introduced in Java 5, fundamentally serve to enable types (classes and interfaces) to be parameters when defining classes, interfaces, and methods. This remarkable feature allows Java developers to create a single class, method, or interface, while accommodating a wide range of data types. The general form of a generic class can be depicted as follows:</p>



<div class="wp-block-kevinbatdorf-code-block-pro" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:clamp(14px, .875rem, 21px);font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:clamp(20px, 1.25rem, 30px);--cbp-tab-width:4;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:10px 0px 10px 16px;margin-bottom:-2px;width:100%;text-align:left;background-color:#2f363c;color:#d3d7dd">Java</span><span role="button" tabindex="0" data-code="class GenericClass&lt;T&gt; {
    private T obj;

    public void add(T obj) {
        this.obj = obj;
    }

    public T get() {
        return obj;
    }
}" style="color:#e1e4e8;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki github-dark" style="background-color: #24292e" tabindex="0"><code><span class="line"><span style="color: #F97583">class</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">GenericClass</span><span style="color: #E1E4E8">&lt;</span><span style="color: #F97583">T</span><span style="color: #E1E4E8">&gt; {</span></span>
<span class="line"><span style="color: #E1E4E8">    </span><span style="color: #F97583">private</span><span style="color: #E1E4E8"> T obj;</span></span>
<span class="line"></span>
<span class="line"><span style="color: #E1E4E8">    </span><span style="color: #F97583">public</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">void</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">add</span><span style="color: #E1E4E8">(T </span><span style="color: #FFAB70">obj</span><span style="color: #E1E4E8">) {</span></span>
<span class="line"><span style="color: #E1E4E8">        </span><span style="color: #79B8FF">this</span><span style="color: #E1E4E8">.obj </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> obj;</span></span>
<span class="line"><span style="color: #E1E4E8">    }</span></span>
<span class="line"></span>
<span class="line"><span style="color: #E1E4E8">    </span><span style="color: #F97583">public</span><span style="color: #E1E4E8"> T </span><span style="color: #B392F0">get</span><span style="color: #E1E4E8">() {</span></span>
<span class="line"><span style="color: #E1E4E8">        </span><span style="color: #F97583">return</span><span style="color: #E1E4E8"> obj;</span></span>
<span class="line"><span style="color: #E1E4E8">    }</span></span>
<span class="line"><span style="color: #E1E4E8">}</span></span></code></pre></div>



<p>In this generic class definition, <code>T</code> is a type parameter that will be replaced by a real type when an object of <code>GenericClass</code> is created. The <code>T</code> allows you to work with different data types while preserving type safety.</p>



<h3 class="wp-block-heading"><strong>The Utility of Generics</strong></h3>



<p>Generics confer a multitude of benefits, with type safety being the prime advantage. Through generics, developers can detect type errors at compile time, rather than at runtime, thereby avoiding potential runtime crashes and fostering more robust applications. This early error detection mechanism ushers in a safer and more secure coding environment.</p>



<p>Moreover, generics obviate the need for type casting, facilitating cleaner and more readable code. In the absence of generics, one would have to resort to type casting objects from the class <code>Object</code>, incurring the risk of <code>ClassCastException</code> at runtime. Generics eliminate this risk, as demonstrated below:</p>



<div class="wp-block-kevinbatdorf-code-block-pro" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:clamp(14px, .875rem, 21px);font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:clamp(20px, 1.25rem, 30px);--cbp-tab-width:4;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:10px 0px 10px 16px;margin-bottom:-2px;width:100%;text-align:left;background-color:#2f363c;color:#d3d7dd">Java</span><span role="button" tabindex="0" data-code="// With Generics:
List&lt;String&gt; genericList = new ArrayList&lt;&gt;();
genericList.add(&quot;Hello&quot;);
String str1 = genericList.get(0); // No need for casting

// Without Generics:
List anotherList = new ArrayList();
anotherList.add(&quot;Hello&quot;);
String str2 = (String) anotherList.get(0); // Need for casting every time an object is retrieved" style="color:#e1e4e8;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki github-dark" style="background-color: #24292e" tabindex="0"><code><span class="line"><span style="color: #6A737D">// With Generics:</span></span>
<span class="line"><span style="color: #E1E4E8">List&lt;</span><span style="color: #F97583">String</span><span style="color: #E1E4E8">&gt; genericList </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">new</span><span style="color: #E1E4E8"> ArrayList&lt;&gt;();</span></span>
<span class="line"><span style="color: #E1E4E8">genericList.</span><span style="color: #B392F0">add</span><span style="color: #E1E4E8">(</span><span style="color: #9ECBFF">&quot;Hello&quot;</span><span style="color: #E1E4E8">);</span></span>
<span class="line"><span style="color: #E1E4E8">String str1 </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> genericList.</span><span style="color: #B392F0">get</span><span style="color: #E1E4E8">(</span><span style="color: #79B8FF">0</span><span style="color: #E1E4E8">); </span><span style="color: #6A737D">// No need for casting</span></span>
<span class="line"></span>
<span class="line"><span style="color: #6A737D">// Without Generics:</span></span>
<span class="line"><span style="color: #E1E4E8">List anotherList </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">new</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">ArrayList</span><span style="color: #E1E4E8">();</span></span>
<span class="line"><span style="color: #E1E4E8">anotherList.</span><span style="color: #B392F0">add</span><span style="color: #E1E4E8">(</span><span style="color: #9ECBFF">&quot;Hello&quot;</span><span style="color: #E1E4E8">);</span></span>
<span class="line"><span style="color: #E1E4E8">String str2 </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> (String) anotherList.</span><span style="color: #B392F0">get</span><span style="color: #E1E4E8">(</span><span style="color: #79B8FF">0</span><span style="color: #E1E4E8">); </span><span style="color: #6A737D">// Need for casting every time an object is retrieved</span></span></code></pre></div>



<p>By leveraging generics, developers can reuse code more effectively. A single generic class can work with different types, reducing the necessity to create multiple classes to handle different data types, thus promoting code reusability.</p>



<p>Lastly, generics enable developers to implement generic algorithms that work on collections of different types, fostering flexibility and expandability in code structures.</p>



<p>To put it succinctly, you can liken generics to a set of architectural plans. Just as a single blueprint can serve to construct various houses with different attributes (like different types of bricks, paints, etc.), a single generic class or method can operate on different data types, adapting its behavior based on the type it is operating on.</p>



<h2 class="wp-block-heading"><strong>Wildcards in Generics</strong></h2>



<p>Generics in Java allow for type flexibility while maintaining type safety through a feature known as wildcards, represented by the symbol <code>?</code>. These wildcards can be used in variable declarations and can stand for an unknown type. Below, we will explore the three variations of wildcards—unbounded, upper bounded, and lower bounded—each with its own distinct characteristics and use cases. Alongside, we will delve into examples to illustrate the practical applications of each variant.</p>



<h3 class="wp-block-heading"><strong>Unbounded Wildcards</strong></h3>



<p>An unbounded wildcard represents an unknown type. It is essentially a way to work with generics when you have no constraint on the type of data being used in your collection. Though it doesn&#8217;t provide strong type safety, it can be useful in scenarios where the operations are generic and are not dependent on a specific type.</p>



<div class="wp-block-kevinbatdorf-code-block-pro" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:clamp(14px, .875rem, 21px);font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:clamp(20px, 1.25rem, 30px);--cbp-tab-width:4;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:10px 0px 10px 16px;margin-bottom:-2px;width:100%;text-align:left;background-color:#2f363c;color:#d3d7dd">Java</span><span role="button" tabindex="0" data-code="public void printList(List&lt;?&gt; list) {
    for (Object obj : list) {
        System.out.println(obj);
    }
}

// Usage
List&lt;Integer&gt; intList = Arrays.asList(1, 2, 3);
List&lt;String&gt; strList = Arrays.asList(&quot;A&quot;, &quot;B&quot;, &quot;C&quot;);
printList(intList);
printList(strList);" style="color:#e1e4e8;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki github-dark" style="background-color: #24292e" tabindex="0"><code><span class="line"><span style="color: #F97583">public</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">void</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">printList</span><span style="color: #E1E4E8">(List</span><span style="color: #F97583">&lt;?&gt;</span><span style="color: #E1E4E8"> list) {</span></span>
<span class="line"><span style="color: #E1E4E8">    </span><span style="color: #F97583">for</span><span style="color: #E1E4E8"> (Object obj </span><span style="color: #F97583">:</span><span style="color: #E1E4E8"> list) {</span></span>
<span class="line"><span style="color: #E1E4E8">        System.out.</span><span style="color: #B392F0">println</span><span style="color: #E1E4E8">(obj);</span></span>
<span class="line"><span style="color: #E1E4E8">    }</span></span>
<span class="line"><span style="color: #E1E4E8">}</span></span>
<span class="line"></span>
<span class="line"><span style="color: #6A737D">// Usage</span></span>
<span class="line"><span style="color: #E1E4E8">List&lt;</span><span style="color: #F97583">Integer</span><span style="color: #E1E4E8">&gt; intList </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> Arrays.</span><span style="color: #B392F0">asList</span><span style="color: #E1E4E8">(</span><span style="color: #79B8FF">1</span><span style="color: #E1E4E8">, </span><span style="color: #79B8FF">2</span><span style="color: #E1E4E8">, </span><span style="color: #79B8FF">3</span><span style="color: #E1E4E8">);</span></span>
<span class="line"><span style="color: #E1E4E8">List&lt;</span><span style="color: #F97583">String</span><span style="color: #E1E4E8">&gt; strList </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> Arrays.</span><span style="color: #B392F0">asList</span><span style="color: #E1E4E8">(</span><span style="color: #9ECBFF">&quot;A&quot;</span><span style="color: #E1E4E8">, </span><span style="color: #9ECBFF">&quot;B&quot;</span><span style="color: #E1E4E8">, </span><span style="color: #9ECBFF">&quot;C&quot;</span><span style="color: #E1E4E8">);</span></span>
<span class="line"><span style="color: #B392F0">printList</span><span style="color: #E1E4E8">(intList);</span></span>
<span class="line"><span style="color: #B392F0">printList</span><span style="color: #E1E4E8">(strList);</span></span></code></pre></div>



<p>In this code snippet, <code>printList</code> method accepts a list of any type, allowing both a list of integers and a list of strings to be passed to it.</p>



<h3 class="wp-block-heading"><strong>Upper Bounded Wildcards</strong></h3>



<p>Upper bounded wildcards are employed when you want to restrict the unknown type to be of a specific type or a subtype of that. It is defined with the syntax <code>? extends TypeName</code>. It grants us the assurance that the type is either <code>TypeName</code> or some subtype of it, providing a bounded level of flexibility.</p>



<div class="wp-block-kevinbatdorf-code-block-pro" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:clamp(14px, .875rem, 21px);font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:clamp(20px, 1.25rem, 30px);--cbp-tab-width:4;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:10px 0px 10px 16px;margin-bottom:-2px;width:100%;text-align:left;background-color:#2f363c;color:#d3d7dd">Java</span><span role="button" tabindex="0" data-code="public double sumOfList(List&lt;? extends Number&gt; list) {
    double s = 0.0;
    for (Number n : list) {
        s += n.doubleValue();
    }
    return s;
}

// Usage
List&lt;Integer&gt; intList = Arrays.asList(1, 2, 3);
List&lt;Double&gt; doubleList = Arrays.asList(1.1, 2.2, 3.3);
System.out.println(&quot;Sum: &quot; + sumOfList(intList));
System.out.println(&quot;Sum: &quot; + sumOfList(doubleList));" style="color:#e1e4e8;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki github-dark" style="background-color: #24292e" tabindex="0"><code><span class="line"><span style="color: #F97583">public</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">double</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">sumOfList</span><span style="color: #E1E4E8">(List</span><span style="color: #F97583">&lt;?</span><span style="color: #E1E4E8"> extends Number</span><span style="color: #F97583">&gt;</span><span style="color: #E1E4E8"> list) {</span></span>
<span class="line"><span style="color: #E1E4E8">    </span><span style="color: #F97583">double</span><span style="color: #E1E4E8"> s </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> </span><span style="color: #79B8FF">0.0</span><span style="color: #E1E4E8">;</span></span>
<span class="line"><span style="color: #E1E4E8">    </span><span style="color: #F97583">for</span><span style="color: #E1E4E8"> (Number n </span><span style="color: #F97583">:</span><span style="color: #E1E4E8"> list) {</span></span>
<span class="line"><span style="color: #E1E4E8">        s </span><span style="color: #F97583">+=</span><span style="color: #E1E4E8"> n.</span><span style="color: #B392F0">doubleValue</span><span style="color: #E1E4E8">();</span></span>
<span class="line"><span style="color: #E1E4E8">    }</span></span>
<span class="line"><span style="color: #E1E4E8">    </span><span style="color: #F97583">return</span><span style="color: #E1E4E8"> s;</span></span>
<span class="line"><span style="color: #E1E4E8">}</span></span>
<span class="line"></span>
<span class="line"><span style="color: #6A737D">// Usage</span></span>
<span class="line"><span style="color: #E1E4E8">List&lt;</span><span style="color: #F97583">Integer</span><span style="color: #E1E4E8">&gt; intList </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> Arrays.</span><span style="color: #B392F0">asList</span><span style="color: #E1E4E8">(</span><span style="color: #79B8FF">1</span><span style="color: #E1E4E8">, </span><span style="color: #79B8FF">2</span><span style="color: #E1E4E8">, </span><span style="color: #79B8FF">3</span><span style="color: #E1E4E8">);</span></span>
<span class="line"><span style="color: #E1E4E8">List&lt;</span><span style="color: #F97583">Double</span><span style="color: #E1E4E8">&gt; doubleList </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> Arrays.</span><span style="color: #B392F0">asList</span><span style="color: #E1E4E8">(</span><span style="color: #79B8FF">1.1</span><span style="color: #E1E4E8">, </span><span style="color: #79B8FF">2.2</span><span style="color: #E1E4E8">, </span><span style="color: #79B8FF">3.3</span><span style="color: #E1E4E8">);</span></span>
<span class="line"><span style="color: #E1E4E8">System.out.</span><span style="color: #B392F0">println</span><span style="color: #E1E4E8">(</span><span style="color: #9ECBFF">&quot;Sum: &quot;</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">+</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">sumOfList</span><span style="color: #E1E4E8">(intList));</span></span>
<span class="line"><span style="color: #E1E4E8">System.out.</span><span style="color: #B392F0">println</span><span style="color: #E1E4E8">(</span><span style="color: #9ECBFF">&quot;Sum: &quot;</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">+</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">sumOfList</span><span style="color: #E1E4E8">(doubleList));</span></span></code></pre></div>



<p>In the example, the <code>sumOfList</code> method can accept lists of any class type that extends <code>Number</code>, ensuring type safety while computing the sum.</p>



<h3 class="wp-block-heading"><strong>Lower Bounded Wildcards</strong></h3>



<p>Lower bounded wildcards are utilized when you desire to restrict the unknown type to be of a specific type or a supertype of that, using the syntax <code>? super TypeName</code>. This facilitates operations where you are writing data into structures by ensuring that the type is a superclass of a certain type.</p>



<div class="wp-block-kevinbatdorf-code-block-pro" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:clamp(14px, .875rem, 21px);font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:clamp(20px, 1.25rem, 30px);--cbp-tab-width:4;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:10px 0px 10px 16px;margin-bottom:-2px;width:100%;text-align:left;background-color:#2f363c;color:#d3d7dd">Java</span><span role="button" tabindex="0" data-code="public void addNumbers(List&lt;? super Integer&gt; list) {
    for (int i = 1; i &lt;= 10; i++) {
        list.add(i);
    }
}

// Usage
List&lt;Number&gt; numList = new ArrayList&lt;&gt;();
addNumbers(numList);
System.out.println(&quot;List: &quot; + numList);" style="color:#e1e4e8;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki github-dark" style="background-color: #24292e" tabindex="0"><code><span class="line"><span style="color: #F97583">public</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">void</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">addNumbers</span><span style="color: #E1E4E8">(List</span><span style="color: #F97583">&lt;?</span><span style="color: #E1E4E8"> </span><span style="color: #79B8FF">super</span><span style="color: #E1E4E8"> Integer</span><span style="color: #F97583">&gt;</span><span style="color: #E1E4E8"> list) {</span></span>
<span class="line"><span style="color: #E1E4E8">    </span><span style="color: #F97583">for</span><span style="color: #E1E4E8"> (</span><span style="color: #F97583">int</span><span style="color: #E1E4E8"> i </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> </span><span style="color: #79B8FF">1</span><span style="color: #E1E4E8">; i </span><span style="color: #F97583">&lt;=</span><span style="color: #E1E4E8"> </span><span style="color: #79B8FF">10</span><span style="color: #E1E4E8">; i</span><span style="color: #F97583">++</span><span style="color: #E1E4E8">) {</span></span>
<span class="line"><span style="color: #E1E4E8">        list.</span><span style="color: #B392F0">add</span><span style="color: #E1E4E8">(i);</span></span>
<span class="line"><span style="color: #E1E4E8">    }</span></span>
<span class="line"><span style="color: #E1E4E8">}</span></span>
<span class="line"></span>
<span class="line"><span style="color: #6A737D">// Usage</span></span>
<span class="line"><span style="color: #E1E4E8">List&lt;</span><span style="color: #F97583">Number</span><span style="color: #E1E4E8">&gt; numList </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">new</span><span style="color: #E1E4E8"> ArrayList&lt;&gt;();</span></span>
<span class="line"><span style="color: #B392F0">addNumbers</span><span style="color: #E1E4E8">(numList);</span></span>
<span class="line"><span style="color: #E1E4E8">System.out.</span><span style="color: #B392F0">println</span><span style="color: #E1E4E8">(</span><span style="color: #9ECBFF">&quot;List: &quot;</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">+</span><span style="color: #E1E4E8"> numList);</span></span></code></pre></div>



<p>In the demonstrated scenario, the <code>addNumbers</code> method can add integers to a list that accepts integer values or the values of any superclass of <code>Integer</code>, such as a list of <code>Number</code>.</p>



<p>Understanding and utilizing the various wildcard types effectively can allow you to maintain type safety while availing a degree of flexibility in your code. Knowing when to use which wildcard can make your generic methods more flexible and adaptable to different requirements.</p>



<h2 class="wp-block-heading"><strong>Advanced Concepts</strong></h2>



<h3 class="wp-block-heading"><strong>Generic Methods and Varargs</strong></h3>



<p>Java supports varargs methods that can accept zero or more arguments of a specified type. Interestingly, you can have generic methods that accept varargs. Let’s consider an example:</p>



<div class="wp-block-kevinbatdorf-code-block-pro" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:clamp(14px, .875rem, 21px);font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:clamp(20px, 1.25rem, 30px);--cbp-tab-width:4;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:10px 0px 10px 16px;margin-bottom:-2px;width:100%;text-align:left;background-color:#2f363c;color:#d3d7dd">Java</span><span role="button" tabindex="0" data-code="@SafeVarargs
public static &lt;T&gt; List&lt;T&gt; mergeToList(T... elements) {
    return Arrays.stream(elements).collect(Collectors.toList());
}" style="color:#e1e4e8;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki github-dark" style="background-color: #24292e" tabindex="0"><code><span class="line"><span style="color: #E1E4E8">@</span><span style="color: #F97583">SafeVarargs</span></span>
<span class="line"><span style="color: #F97583">public</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">static</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">&lt;</span><span style="color: #E1E4E8">T</span><span style="color: #F97583">&gt;</span><span style="color: #E1E4E8"> List</span><span style="color: #F97583">&lt;</span><span style="color: #E1E4E8">T</span><span style="color: #F97583">&gt;</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">mergeToList</span><span style="color: #E1E4E8">(T... elements) {</span></span>
<span class="line"><span style="color: #E1E4E8">    </span><span style="color: #F97583">return</span><span style="color: #E1E4E8"> Arrays.</span><span style="color: #B392F0">stream</span><span style="color: #E1E4E8">(elements).</span><span style="color: #B392F0">collect</span><span style="color: #E1E4E8">(Collectors.</span><span style="color: #B392F0">toList</span><span style="color: #E1E4E8">());</span></span>
<span class="line"><span style="color: #E1E4E8">}</span></span></code></pre></div>



<h3 class="wp-block-heading"><strong>Type Inference and Generics</strong></h3>



<p>In the realm of Java generics, type inference plays a pivotal role in reducing verbosity and facilitating more readable and maintainable code. This mechanism allows the Java compiler to deduce the type arguments of a generic method invocation. The compiler leverages the context in which the method is called and the types of arguments passed to the method to infer the appropriate type parameters. In this section, we explore type inference in depth, discussing its working and demonstrating its utility through examples.</p>



<h4 class="wp-block-heading"><strong>Understanding Type Inference</strong></h4>



<p>At its core, type inference is about the Java compiler determining the type parameters of a generic method without explicit declaration from the programmer. This happens automatically based on the method arguments and the context in which the method is invoked. Let&#8217;s take a look at a simple generic method and see how type inference operates:</p>



<div class="wp-block-kevinbatdorf-code-block-pro" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:clamp(14px, .875rem, 21px);font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:clamp(20px, 1.25rem, 30px);--cbp-tab-width:4;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:10px 0px 10px 16px;margin-bottom:-2px;width:100%;text-align:left;background-color:#2f363c;color:#d3d7dd">Java</span><span role="button" tabindex="0" data-code="public class TypeInferenceExample {
    public static &lt;T&gt; void display(T item) {
        System.out.println(item);
    }

    public static void main(String[] args) {
        display(&quot;Hello, World!&quot;); // T is inferred to be String
        display(123); // T is inferred to be Integer
    }
}" style="color:#e1e4e8;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki github-dark" style="background-color: #24292e" tabindex="0"><code><span class="line"><span style="color: #F97583">public</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">class</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">TypeInferenceExample</span><span style="color: #E1E4E8"> {</span></span>
<span class="line"><span style="color: #E1E4E8">    </span><span style="color: #F97583">public</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">static</span><span style="color: #E1E4E8"> &lt;</span><span style="color: #F97583">T</span><span style="color: #E1E4E8">&gt; </span><span style="color: #F97583">void</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">display</span><span style="color: #E1E4E8">(T </span><span style="color: #FFAB70">item</span><span style="color: #E1E4E8">) {</span></span>
<span class="line"><span style="color: #E1E4E8">        System.out.</span><span style="color: #B392F0">println</span><span style="color: #E1E4E8">(item);</span></span>
<span class="line"><span style="color: #E1E4E8">    }</span></span>
<span class="line"></span>
<span class="line"><span style="color: #E1E4E8">    </span><span style="color: #F97583">public</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">static</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">void</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">main</span><span style="color: #E1E4E8">(</span><span style="color: #F97583">String</span><span style="color: #E1E4E8">[] </span><span style="color: #FFAB70">args</span><span style="color: #E1E4E8">) {</span></span>
<span class="line"><span style="color: #E1E4E8">        </span><span style="color: #B392F0">display</span><span style="color: #E1E4E8">(</span><span style="color: #9ECBFF">&quot;Hello, World!&quot;</span><span style="color: #E1E4E8">); </span><span style="color: #6A737D">// T is inferred to be String</span></span>
<span class="line"><span style="color: #E1E4E8">        </span><span style="color: #B392F0">display</span><span style="color: #E1E4E8">(</span><span style="color: #79B8FF">123</span><span style="color: #E1E4E8">); </span><span style="color: #6A737D">// T is inferred to be Integer</span></span>
<span class="line"><span style="color: #E1E4E8">    }</span></span>
<span class="line"><span style="color: #E1E4E8">}</span></span></code></pre></div>



<p>In the above code snippet, we define a generic method <code>display</code> which accepts a single argument of type <code>T</code>. When we call this method with different types of arguments, the compiler automatically infers the type parameter <code>T</code> based on the type of the argument passed.</p>



<h4 class="wp-block-heading"><strong>Target Types</strong></h4>



<p>Java leverages the target type, the type that Java expects depending on where the expression appears, to infer the type parameters. The target type can influence the type of an expression, enhancing the preciseness of type inference. Let us understand this with an example:</p>



<div class="wp-block-kevinbatdorf-code-block-pro" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:clamp(14px, .875rem, 21px);font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:clamp(20px, 1.25rem, 30px);--cbp-tab-width:4;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:10px 0px 10px 16px;margin-bottom:-2px;width:100%;text-align:left;background-color:#2f363c;color:#d3d7dd">Java</span><span role="button" tabindex="0" data-code="List&lt;String&gt; list = Collections.emptyList(); // The target type is List&lt;String&gt;" style="color:#e1e4e8;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki github-dark" style="background-color: #24292e" tabindex="0"><code><span class="line"><span style="color: #E1E4E8">List&lt;</span><span style="color: #F97583">String</span><span style="color: #E1E4E8">&gt; list </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> Collections.</span><span style="color: #B392F0">emptyList</span><span style="color: #E1E4E8">(); </span><span style="color: #6A737D">// The target type is List&lt;String&gt;</span></span></code></pre></div>



<p>Here, <code>Collections.emptyList()</code> returns a list of a specific inferred type based on the target type, which is <code>List&lt;String&gt;</code>. The compiler uses this information to infer the specific type for the generic method invocation.</p>



<h4 class="wp-block-heading"><strong>Limitations of Type Inference</strong></h4>



<p>While type inference works seamlessly in many scenarios, it has its limitations. In complex scenarios with nested generics or method chains, the compiler might not always be able to infer the correct type, necessitating explicit type arguments to guide the compiler. Below is an example illustrating such a scenario:</p>



<div class="wp-block-kevinbatdorf-code-block-pro" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:clamp(14px, .875rem, 21px);font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:clamp(20px, 1.25rem, 30px);--cbp-tab-width:4;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:10px 0px 10px 16px;margin-bottom:-2px;width:100%;text-align:left;background-color:#2f363c;color:#d3d7dd">Java</span><span role="button" tabindex="0" data-code="Stream.of(&quot;a&quot;, &quot;b&quot;, &quot;c&quot;)
      .map(s -&gt; s.toUpperCase())
      .forEach(s -&gt; System.out.println(s));" style="color:#e1e4e8;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki github-dark" style="background-color: #24292e" tabindex="0"><code><span class="line"><span style="color: #E1E4E8">Stream.</span><span style="color: #B392F0">of</span><span style="color: #E1E4E8">(</span><span style="color: #9ECBFF">&quot;a&quot;</span><span style="color: #E1E4E8">, </span><span style="color: #9ECBFF">&quot;b&quot;</span><span style="color: #E1E4E8">, </span><span style="color: #9ECBFF">&quot;c&quot;</span><span style="color: #E1E4E8">)</span></span>
<span class="line"><span style="color: #E1E4E8">      .</span><span style="color: #B392F0">map</span><span style="color: #E1E4E8">(s </span><span style="color: #F97583">-&gt;</span><span style="color: #E1E4E8"> s.</span><span style="color: #B392F0">toUpperCase</span><span style="color: #E1E4E8">())</span></span>
<span class="line"><span style="color: #E1E4E8">      .</span><span style="color: #B392F0">forEach</span><span style="color: #E1E4E8">(s </span><span style="color: #F97583">-&gt;</span><span style="color: #E1E4E8"> System.out.</span><span style="color: #B392F0">println</span><span style="color: #E1E4E8">(s));</span></span></code></pre></div>



<p>In the above example, the compiler is able to infer the type correctly. However, as you add more complexity to the method chain, there might be situations where the compiler fails to infer the correct type, leading to compilation errors.</p>



<p>Type inference with generics is a feature that bestows Java developers with the gift of less verbose and more readable code. By understanding how the Java compiler deduces type parameters automatically based on method arguments and context, developers can write generic methods that are both powerful and easy to use. While the mechanism operates flawlessly in a plethora of situations, being aware of its limitations is key to effectively utilizing type inference in complex scenarios.</p>



<h3 class="wp-block-heading"><strong>Reflection and Generics</strong></h3>



<p>In the Java programming language, reflection allows your code to inspect and manipulate the properties of classes, interfaces, fields, and methods at runtime. It is a powerful tool that can offer great flexibility in your applications. However, when generics meet reflection, a series of complications can arise, mainly due to a mechanism known as type erasure. In this section, we will dive deep into the nuances of using reflection in conjunction with generics, illustrating the limitations imposed by type erasure and showcasing how to circumvent potential runtime errors through careful considerations.</p>



<h4 class="wp-block-heading"><strong>Understanding Type Erasure</strong></h4>



<p>Before diving into the heart of the matter, it is pivotal to grasp the concept of type erasure. In Java, type erasure ensures backward compatibility with older versions of Java that do not support generics. During the compilation process, the compiler removes all type parameters and replaces them with their bounds or <code>Object</code> if the type parameters are unbounded. Here is an illustrative example:</p>



<div class="wp-block-kevinbatdorf-code-block-pro" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:clamp(14px, .875rem, 21px);font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:clamp(20px, 1.25rem, 30px);--cbp-tab-width:4;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:10px 0px 10px 16px;margin-bottom:-2px;width:100%;text-align:left;background-color:#2f363c;color:#d3d7dd">Java</span><span role="button" tabindex="0" data-code="List&lt;String&gt; stringList = new ArrayList&lt;&gt;();
List&lt;Integer&gt; integerList = new ArrayList&lt;&gt;();

// After type erasure
List stringList = new ArrayList(); // Type parameter is erased
List integerList = new ArrayList(); // Type parameter is erased" style="color:#e1e4e8;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki github-dark" style="background-color: #24292e" tabindex="0"><code><span class="line"><span style="color: #E1E4E8">List&lt;</span><span style="color: #F97583">String</span><span style="color: #E1E4E8">&gt; stringList </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">new</span><span style="color: #E1E4E8"> ArrayList&lt;&gt;();</span></span>
<span class="line"><span style="color: #E1E4E8">List&lt;</span><span style="color: #F97583">Integer</span><span style="color: #E1E4E8">&gt; integerList </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">new</span><span style="color: #E1E4E8"> ArrayList&lt;&gt;();</span></span>
<span class="line"></span>
<span class="line"><span style="color: #6A737D">// After type erasure</span></span>
<span class="line"><span style="color: #E1E4E8">List stringList </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">new</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">ArrayList</span><span style="color: #E1E4E8">(); </span><span style="color: #6A737D">// Type parameter is erased</span></span>
<span class="line"><span style="color: #E1E4E8">List integerList </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">new</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">ArrayList</span><span style="color: #E1E4E8">(); </span><span style="color: #6A737D">// Type parameter is erased</span></span></code></pre></div>



<p>As seen in the example, after type erasure, the type parameters of both lists are removed, and the lists are treated as raw types.</p>



<h4 class="wp-block-heading"><strong>The Dilemma with Reflection and Generics</strong></h4>



<p>Given that type information is erased at runtime, reflection cannot be used to directly query parameterized types. When you introspect a generic type at runtime, the runtime type information only retains the raw type information, without any indication of the generic type parameters. Let us examine this phenomenon with a code snippet:</p>



<div class="wp-block-kevinbatdorf-code-block-pro" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:clamp(14px, .875rem, 21px);font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:clamp(20px, 1.25rem, 30px);--cbp-tab-width:4;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:10px 0px 10px 16px;margin-bottom:-2px;width:100%;text-align:left;background-color:#2f363c;color:#d3d7dd">Java</span><span role="button" tabindex="0" data-code="public static void main(String[] args) throws NoSuchFieldException {
    Field field = MyClass.class.getDeclaredField(&quot;myList&quot;);
    ParameterizedType type = (ParameterizedType) field.getGenericType();
    System.out.println(type.getActualTypeArguments()[0]);
}

static class MyClass {
    private List&lt;String&gt; myList;
}" style="color:#e1e4e8;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki github-dark" style="background-color: #24292e" tabindex="0"><code><span class="line"><span style="color: #F97583">public</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">static</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">void</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">main</span><span style="color: #E1E4E8">(</span><span style="color: #F97583">String</span><span style="color: #E1E4E8">[] args) throws NoSuchFieldException {</span></span>
<span class="line"><span style="color: #E1E4E8">    Field field </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> MyClass.class.</span><span style="color: #B392F0">getDeclaredField</span><span style="color: #E1E4E8">(</span><span style="color: #9ECBFF">&quot;myList&quot;</span><span style="color: #E1E4E8">);</span></span>
<span class="line"><span style="color: #E1E4E8">    ParameterizedType type </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> (ParameterizedType) field.</span><span style="color: #B392F0">getGenericType</span><span style="color: #E1E4E8">();</span></span>
<span class="line"><span style="color: #E1E4E8">    System.out.</span><span style="color: #B392F0">println</span><span style="color: #E1E4E8">(type.</span><span style="color: #B392F0">getActualTypeArguments</span><span style="color: #E1E4E8">()[</span><span style="color: #79B8FF">0</span><span style="color: #E1E4E8">]);</span></span>
<span class="line"><span style="color: #E1E4E8">}</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F97583">static</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">class</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">MyClass</span><span style="color: #E1E4E8"> {</span></span>
<span class="line"><span style="color: #E1E4E8">    </span><span style="color: #F97583">private</span><span style="color: #E1E4E8"> List&lt;</span><span style="color: #F97583">String</span><span style="color: #E1E4E8">&gt; myList;</span></span>
<span class="line"><span style="color: #E1E4E8">}</span></span></code></pre></div>



<p>In the code above, we&#8217;re attempting to extract the parameterized type of <code>myList</code> field using reflection. However, due to type erasure, the JVM does not retain the actual type parameter (<code>String</code>) at runtime. Thus, executing this snippet will raise a <code>ClassCastException</code> because the generic type information is not available at runtime.</p>



<h4 class="wp-block-heading"><strong>Navigating the Pitfalls</strong></h4>



<p>Despite the limitations, there are still ways to work with generics through reflection, albeit with careful consideration. One common strategy is to pass Class objects representing the type parameters, explicitly conveying the type information that would otherwise be lost due to type erasure. Here is how you can do it:</p>



<div class="wp-block-kevinbatdorf-code-block-pro" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:clamp(14px, .875rem, 21px);font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:clamp(20px, 1.25rem, 30px);--cbp-tab-width:4;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:10px 0px 10px 16px;margin-bottom:-2px;width:100%;text-align:left;background-color:#2f363c;color:#d3d7dd">Java</span><span role="button" tabindex="0" data-code="public static &lt;T&gt; void genericMethod(Class&lt;T&gt; typeParameterClass) {
    // Use the typeParameterClass object in reflection operations
}

// Usage
genericMethod(String.class);" style="color:#e1e4e8;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki github-dark" style="background-color: #24292e" tabindex="0"><code><span class="line"><span style="color: #F97583">public</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">static</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">&lt;</span><span style="color: #E1E4E8">T</span><span style="color: #F97583">&gt;</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">void</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">genericMethod</span><span style="color: #E1E4E8">(Class</span><span style="color: #F97583">&lt;</span><span style="color: #E1E4E8">T</span><span style="color: #F97583">&gt;</span><span style="color: #E1E4E8"> typeParameterClass) {</span></span>
<span class="line"><span style="color: #E1E4E8">    </span><span style="color: #6A737D">// Use the typeParameterClass object in reflection operations</span></span>
<span class="line"><span style="color: #E1E4E8">}</span></span>
<span class="line"></span>
<span class="line"><span style="color: #6A737D">// Usage</span></span>
<span class="line"><span style="color: #B392F0">genericMethod</span><span style="color: #E1E4E8">(String.class);</span></span></code></pre></div>



<p>In this scenario, we are passing the <code>Class</code> object corresponding to the type parameter to the <code>genericMethod</code>, thereby preserving the type information and enabling reflection operations that are aware of the generic type.</p>



<p>Reflecting on generics in Java presents a distinctive set of challenges, chiefly due to the process of type erasure that omits type parameter information at runtime. As a result, developers must tread with caution to prevent runtime errors stemming from the unavailability of generic type information during reflection operations. However, by understanding the underlying principles of type erasure and adopting strategies to preserve type information, such as passing Class objects representing type parameters, you can leverage both generics and reflection effectively in your Java applications, albeit with a careful and considered approach.</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<p>Generics, an essential concept in Java, enhance code reusability and type safety. Starting from defining generic classes and methods, to understanding bounded type parameters, wildcards, and the impact of type erasure, this guide has walked you through the foundations and advanced topics surrounding Generics in Java.</p>



<p>As you continue on your journey with Java programming, take time to experiment with creating your generic classes and methods, understanding how wildcards work, and the nuances of type erasure. Remember that a deep understanding of Generics will not only help you to write cleaner, more stable code but also to decipher and work efficiently with complex codebases. Happy coding!</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Mastering Java Streams: From Basics to Advanced Techniques</title>
		<link>https://blog.j-dev.app/java-streams-from-basics-to-advanced-techniques/</link>
		
		<dc:creator><![CDATA[JuanC]]></dc:creator>
		<pubDate>Fri, 01 Sep 2023 21:33:39 +0000</pubDate>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Streams]]></category>
		<guid isPermaLink="false">https://blog.j-dev.app/?page_id=179</guid>

					<description><![CDATA[Streams in Java represent a big leap forward in making collections manipulations easy, efficient, and clean. They are one of the major features introduced in Java 8 and have since become an integral part of modern Java programming. This article aims to be a comprehensive guide to understanding and working with Streams in Java. Whether [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p>Streams in Java represent a big leap forward in making collections manipulations easy, efficient, and clean. They are one of the major features introduced in Java 8 and have since become an integral part of modern Java programming. This article aims to be a comprehensive guide to understanding and working with Streams in Java. Whether you&#8217;re a beginner just diving into Java or an experienced programmer looking to broaden your skill set, this guide is intended to provide deep insights into what Java Streams are and how they can be effectively used.</p>



<h2 class="wp-block-heading">What is a Stream?</h2>



<p>At the most basic level, a Stream is an abstraction that describes a sequence of elements and a set of computational operations that can be performed on those elements. It is not a data structure; rather, it provides a higher-level, declarative API over actual data structures like collections (e.g., <code>List</code>, <code>Set</code>), arrays, or I/O channels.</p>



<p>Unlike collections, streams are lazy; they don&#8217;t perform any operations until absolutely necessary. This makes them extremely efficient, especially for large datasets. Imagine a scenario where you have a list of a million integers, and you need to find the first number that is divisible by 5 and greater than 100. A traditional loop would iterate over each element, perform the calculations, and store intermediate data. In contrast, a Stream will only process elements until it finds the first match, without storing any intermediate data.</p>



<h2 class="wp-block-heading">Creating Streams</h2>



<p>Streams can be created in a number of ways, but the most straightforward approach is from existing collections or arrays. For instance:</p>



<div class="wp-block-kevinbatdorf-code-block-pro" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:clamp(14px, .875rem, 21px);font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:clamp(20px, 1.25rem, 30px);--cbp-tab-width:4;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:10px 0px 10px 16px;margin-bottom:-2px;width:100%;text-align:left;background-color:#2f363c;color:#d3d7dd">Java</span><span role="button" tabindex="0" data-code="// Creating a Stream from a List
List&lt;String&gt; myList = Arrays.asList(&quot;apple&quot;, &quot;banana&quot;, &quot;cherry&quot;);
Stream&lt;String&gt; myStream = myList.stream();

// Creating a Stream from an Array
String[] myArray = {&quot;apple&quot;, &quot;banana&quot;, &quot;cherry&quot;};
Stream&lt;String&gt; myStreamFromArray = Arrays.stream(myArray);" style="color:#e1e4e8;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki github-dark" style="background-color: #24292e" tabindex="0"><code><span class="line"><span style="color: #6A737D">// Creating a Stream from a List</span></span>
<span class="line"><span style="color: #E1E4E8">List&lt;</span><span style="color: #F97583">String</span><span style="color: #E1E4E8">&gt; myList </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> Arrays.</span><span style="color: #B392F0">asList</span><span style="color: #E1E4E8">(</span><span style="color: #9ECBFF">&quot;apple&quot;</span><span style="color: #E1E4E8">, </span><span style="color: #9ECBFF">&quot;banana&quot;</span><span style="color: #E1E4E8">, </span><span style="color: #9ECBFF">&quot;cherry&quot;</span><span style="color: #E1E4E8">);</span></span>
<span class="line"><span style="color: #E1E4E8">Stream&lt;</span><span style="color: #F97583">String</span><span style="color: #E1E4E8">&gt; myStream </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> myList.</span><span style="color: #B392F0">stream</span><span style="color: #E1E4E8">();</span></span>
<span class="line"></span>
<span class="line"><span style="color: #6A737D">// Creating a Stream from an Array</span></span>
<span class="line"><span style="color: #F97583">String</span><span style="color: #E1E4E8">[] myArray </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> {</span><span style="color: #9ECBFF">&quot;apple&quot;</span><span style="color: #E1E4E8">, </span><span style="color: #9ECBFF">&quot;banana&quot;</span><span style="color: #E1E4E8">, </span><span style="color: #9ECBFF">&quot;cherry&quot;</span><span style="color: #E1E4E8">};</span></span>
<span class="line"><span style="color: #E1E4E8">Stream&lt;</span><span style="color: #F97583">String</span><span style="color: #E1E4E8">&gt; myStreamFromArray </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> Arrays.</span><span style="color: #B392F0">stream</span><span style="color: #E1E4E8">(myArray);</span></span></code></pre></div>



<p>You can also create a stream from scratch using <code>Stream.of()</code>:</p>



<div class="wp-block-kevinbatdorf-code-block-pro" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:clamp(14px, .875rem, 21px);font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:clamp(20px, 1.25rem, 30px);--cbp-tab-width:4;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:10px 0px 10px 16px;margin-bottom:-2px;width:100%;text-align:left;background-color:#2f363c;color:#d3d7dd">Java</span><span role="button" tabindex="0" data-code="Stream&lt;String&gt; stringStream = Stream.of(&quot;apple&quot;, &quot;banana&quot;, &quot;cherry&quot;);" style="color:#e1e4e8;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki github-dark" style="background-color: #24292e" tabindex="0"><code><span class="line"><span style="color: #E1E4E8">Stream&lt;</span><span style="color: #F97583">String</span><span style="color: #E1E4E8">&gt; stringStream </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> Stream.</span><span style="color: #B392F0">of</span><span style="color: #E1E4E8">(</span><span style="color: #9ECBFF">&quot;apple&quot;</span><span style="color: #E1E4E8">, </span><span style="color: #9ECBFF">&quot;banana&quot;</span><span style="color: #E1E4E8">, </span><span style="color: #9ECBFF">&quot;cherry&quot;</span><span style="color: #E1E4E8">);</span></span></code></pre></div>



<h2 class="wp-block-heading">Basic Operations</h2>



<h3 class="wp-block-heading">Filtering and Mapping</h3>



<p>Filtering and mapping are two of the fundamental operations you can perform using Java Streams, and understanding them well is crucial for effective Stream manipulation. These operations enable you to transform and pare down collections in a declarative way. Let&#8217;s dive deeper into each of these operations with comprehensive explanations and examples.</p>



<h4 class="wp-block-heading">Filtering</h4>



<p>The <code>filter</code> operation takes a predicate—a function returning a boolean—and applies it to each element in the Stream. If the predicate returns <code>true</code> for a given element, that element remains in the Stream. If the predicate returns <code>false</code>, the element is removed.</p>



<p>Here&#8217;s an example code snippet that demonstrates filtering:</p>



<div class="wp-block-kevinbatdorf-code-block-pro" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:clamp(14px, .875rem, 21px);font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:clamp(20px, 1.25rem, 30px);--cbp-tab-width:4;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:10px 0px 10px 16px;margin-bottom:-2px;width:100%;text-align:left;background-color:#2f363c;color:#d3d7dd">Java</span><span role="button" tabindex="0" data-code="List&lt;Integer&gt; numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
Stream&lt;Integer&gt; filtered = numbers.stream().filter(n -&gt; n % 2 == 0);" style="color:#e1e4e8;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki github-dark" style="background-color: #24292e" tabindex="0"><code><span class="line"><span style="color: #E1E4E8">List&lt;</span><span style="color: #F97583">Integer</span><span style="color: #E1E4E8">&gt; numbers </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> Arrays.</span><span style="color: #B392F0">asList</span><span style="color: #E1E4E8">(</span><span style="color: #79B8FF">1</span><span style="color: #E1E4E8">, </span><span style="color: #79B8FF">2</span><span style="color: #E1E4E8">, </span><span style="color: #79B8FF">3</span><span style="color: #E1E4E8">, </span><span style="color: #79B8FF">4</span><span style="color: #E1E4E8">, </span><span style="color: #79B8FF">5</span><span style="color: #E1E4E8">, </span><span style="color: #79B8FF">6</span><span style="color: #E1E4E8">, </span><span style="color: #79B8FF">7</span><span style="color: #E1E4E8">, </span><span style="color: #79B8FF">8</span><span style="color: #E1E4E8">, </span><span style="color: #79B8FF">9</span><span style="color: #E1E4E8">, </span><span style="color: #79B8FF">10</span><span style="color: #E1E4E8">);</span></span>
<span class="line"><span style="color: #E1E4E8">Stream&lt;</span><span style="color: #F97583">Integer</span><span style="color: #E1E4E8">&gt; filtered </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> numbers.</span><span style="color: #B392F0">stream</span><span style="color: #E1E4E8">().</span><span style="color: #B392F0">filter</span><span style="color: #E1E4E8">(n </span><span style="color: #F97583">-&gt;</span><span style="color: #E1E4E8"> n </span><span style="color: #F97583">%</span><span style="color: #E1E4E8"> </span><span style="color: #79B8FF">2</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">==</span><span style="color: #E1E4E8"> </span><span style="color: #79B8FF">0</span><span style="color: #E1E4E8">);</span></span></code></pre></div>



<p>In this example, we have a list of integers ranging from 1 to 10. We then convert this list to a Stream using the <code>stream()</code> method. Next, we apply the <code>filter</code> operation using the predicate <code>n -&gt; n % 2 == 0</code>. This lambda expression checks if each number in the Stream is even. So, the <code>filter</code> method will go through each element of the Stream, one by one, and keep only the elements that satisfy this condition. As a result, the <code>filtered</code> Stream will contain the numbers 2, 4, 6, 8, and 10.</p>



<h4 class="wp-block-heading">Mapping</h4>



<p>The <code>map</code> operation is used to transform each element in the Stream using a given function. This operation takes a function as an argument, applies this function to each element in the Stream, and produces a new Stream containing the transformed elements.</p>



<p>Here&#8217;s an example code snippet that demonstrates mapping:</p>



<div class="wp-block-kevinbatdorf-code-block-pro" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:clamp(14px, .875rem, 21px);font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:clamp(20px, 1.25rem, 30px);--cbp-tab-width:4;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:10px 0px 10px 16px;margin-bottom:-2px;width:100%;text-align:left;background-color:#2f363c;color:#d3d7dd">Java</span><span role="button" tabindex="0" data-code="Stream&lt;Integer&gt; mapped = numbers.stream().map(n -&gt; n * 2);" style="color:#e1e4e8;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki github-dark" style="background-color: #24292e" tabindex="0"><code><span class="line"><span style="color: #E1E4E8">Stream&lt;</span><span style="color: #F97583">Integer</span><span style="color: #E1E4E8">&gt; mapped </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> numbers.</span><span style="color: #B392F0">stream</span><span style="color: #E1E4E8">().</span><span style="color: #B392F0">map</span><span style="color: #E1E4E8">(n </span><span style="color: #F97583">-&gt;</span><span style="color: #E1E4E8"> n </span><span style="color: #F97583">*</span><span style="color: #E1E4E8"> </span><span style="color: #79B8FF">2</span><span style="color: #E1E4E8">);</span></span></code></pre></div>



<p>In this case, we start with the same list of integers as before and convert it to a Stream. We then use the <code>map</code> method and pass in the lambda expression <code>n -&gt; n * 2</code>. This function doubles the value of each element in the Stream.</p>



<p>When the <code>map</code> function iterates over the elements in the Stream, it applies this lambda expression to each element. Therefore, each number is doubled, and a new Stream is generated that contains these transformed elements. If the original Stream contained the numbers [1, 2, 3, 4, 5], the new Stream would contain [2, 4, 6, 8, 10].</p>



<h4 class="wp-block-heading">Combining Filtering and Mapping</h4>



<p>It&#8217;s common to chain these operations together to perform more complex data transformations. For instance, you can first filter a Stream to keep only the even numbers and then map those numbers to their double:</p>



<div class="wp-block-kevinbatdorf-code-block-pro" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:clamp(14px, .875rem, 21px);font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:clamp(20px, 1.25rem, 30px);--cbp-tab-width:4;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:10px 0px 10px 16px;margin-bottom:-2px;width:100%;text-align:left;background-color:#2f363c;color:#d3d7dd">Java</span><span role="button" tabindex="0" data-code="Stream&lt;Integer&gt; chained = numbers.stream()
		.filter(n -&gt; n % 2 == 0)
		.map(n -&gt; n * 2);" style="color:#e1e4e8;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki github-dark" style="background-color: #24292e" tabindex="0"><code><span class="line"><span style="color: #E1E4E8">Stream&lt;</span><span style="color: #F97583">Integer</span><span style="color: #E1E4E8">&gt; chained </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> numbers.</span><span style="color: #B392F0">stream</span><span style="color: #E1E4E8">()</span></span>
<span class="line"><span style="color: #E1E4E8">		.</span><span style="color: #B392F0">filter</span><span style="color: #E1E4E8">(n </span><span style="color: #F97583">-&gt;</span><span style="color: #E1E4E8"> n </span><span style="color: #F97583">%</span><span style="color: #E1E4E8"> </span><span style="color: #79B8FF">2</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">==</span><span style="color: #E1E4E8"> </span><span style="color: #79B8FF">0</span><span style="color: #E1E4E8">)</span></span>
<span class="line"><span style="color: #E1E4E8">		.</span><span style="color: #B392F0">map</span><span style="color: #E1E4E8">(n </span><span style="color: #F97583">-&gt;</span><span style="color: #E1E4E8"> n </span><span style="color: #F97583">*</span><span style="color: #E1E4E8"> </span><span style="color: #79B8FF">2</span><span style="color: #E1E4E8">);</span></span></code></pre></div>



<p>In this chained operation, the Stream first undergoes filtering, leaving us with the even numbers [2, 4, 6, 8, 10]. The <code>map</code> operation is then applied to these remaining elements, doubling them to create a new Stream containing [4, 8, 12, 16, 20].</p>



<p>These two operations, <code>filter</code> and <code>map</code>, serve as the backbone of Stream manipulations in Java. They allow you to write clean, readable, and efficient code that can perform complex data manipulations in a straightforward way.</p>



<h3 class="wp-block-heading">Collecting Results</h3>



<p>After you&#8217;ve manipulated a Stream using operations like filtering, mapping, or others, the next logical step is to collect these elements back into a more usable data structure or obtain some aggregated results. The <code>collect</code> method in Java&#8217;s Stream API serves precisely this purpose. This method performs what is known as a mutable reduction operation on the elements of the Stream, accumulating them into a result container such as a <code>Collection</code>, <code>StringBuilder</code>, or even a <code>Map</code>. Let&#8217;s delve into some of the various ways to collect data from a Stream, accompanied by detailed explanations and code examples.</p>



<h4 class="wp-block-heading">Basic Collection into a List</h4>



<p>The simplest way to collect elements from a Stream into a list is by using the <code>Collectors.toList()</code> collector. It gathers all elements from a Stream and puts them in a list in encounter order (the order in which elements appear in the Stream).</p>



<div class="wp-block-kevinbatdorf-code-block-pro" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:clamp(14px, .875rem, 21px);font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:clamp(20px, 1.25rem, 30px);--cbp-tab-width:4;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:10px 0px 10px 16px;margin-bottom:-2px;width:100%;text-align:left;background-color:#2f363c;color:#d3d7dd">Java</span><span role="button" tabindex="0" data-code="Stream&lt;Integer&gt; myStream = Stream.of(1, 2, 3, 4, 5);
List&lt;Integer&gt; myList = myStream.collect(Collectors.toList());" style="color:#e1e4e8;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki github-dark" style="background-color: #24292e" tabindex="0"><code><span class="line"><span style="color: #E1E4E8">Stream&lt;</span><span style="color: #F97583">Integer</span><span style="color: #E1E4E8">&gt; myStream </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> Stream.</span><span style="color: #B392F0">of</span><span style="color: #E1E4E8">(</span><span style="color: #79B8FF">1</span><span style="color: #E1E4E8">, </span><span style="color: #79B8FF">2</span><span style="color: #E1E4E8">, </span><span style="color: #79B8FF">3</span><span style="color: #E1E4E8">, </span><span style="color: #79B8FF">4</span><span style="color: #E1E4E8">, </span><span style="color: #79B8FF">5</span><span style="color: #E1E4E8">);</span></span>
<span class="line"><span style="color: #E1E4E8">List&lt;</span><span style="color: #F97583">Integer</span><span style="color: #E1E4E8">&gt; myList </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> myStream.</span><span style="color: #B392F0">collect</span><span style="color: #E1E4E8">(Collectors.</span><span style="color: #B392F0">toList</span><span style="color: #E1E4E8">());</span></span></code></pre></div>



<p>In this example, the <code>myStream</code> Stream contains integers from 1 to 5. We use the <code>collect</code> method with <code>Collectors.toList()</code> to accumulate these integers into a <code>List</code> named <code>myList</code>. After this operation, <code>myList</code> will contain <code>[1, 2, 3, 4, 5]</code>.</p>



<h4 class="wp-block-heading">Collecting into a Set</h4>



<p>Sometimes you may want to eliminate duplicate elements and collect the unique elements into a set. This can be achieved using the <code>Collectors.toSet()</code> collector.</p>



<div class="wp-block-kevinbatdorf-code-block-pro" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:clamp(14px, .875rem, 21px);font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:clamp(20px, 1.25rem, 30px);--cbp-tab-width:4;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:10px 0px 10px 16px;margin-bottom:-2px;width:100%;text-align:left;background-color:#2f363c;color:#d3d7dd">Java</span><span role="button" tabindex="0" data-code="Stream&lt;Integer&gt; myStream = Stream.of(1, 2, 2, 3, 3, 4, 5);
Set&lt;Integer&gt; mySet = myStream.collect(Collectors.toSet());" style="color:#e1e4e8;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki github-dark" style="background-color: #24292e" tabindex="0"><code><span class="line"><span style="color: #E1E4E8">Stream&lt;</span><span style="color: #F97583">Integer</span><span style="color: #E1E4E8">&gt; myStream </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> Stream.</span><span style="color: #B392F0">of</span><span style="color: #E1E4E8">(</span><span style="color: #79B8FF">1</span><span style="color: #E1E4E8">, </span><span style="color: #79B8FF">2</span><span style="color: #E1E4E8">, </span><span style="color: #79B8FF">2</span><span style="color: #E1E4E8">, </span><span style="color: #79B8FF">3</span><span style="color: #E1E4E8">, </span><span style="color: #79B8FF">3</span><span style="color: #E1E4E8">, </span><span style="color: #79B8FF">4</span><span style="color: #E1E4E8">, </span><span style="color: #79B8FF">5</span><span style="color: #E1E4E8">);</span></span>
<span class="line"><span style="color: #E1E4E8">Set&lt;</span><span style="color: #F97583">Integer</span><span style="color: #E1E4E8">&gt; mySet </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> myStream.</span><span style="color: #B392F0">collect</span><span style="color: #E1E4E8">(Collectors.</span><span style="color: #B392F0">toSet</span><span style="color: #E1E4E8">());</span></span></code></pre></div>



<p>Here, <code>myStream</code> contains some duplicate integers. By using <code>Collectors.toSet()</code>, these duplicates are eliminated, and <code>mySet</code> will contain <code>[1, 2, 3, 4, 5]</code>.</p>



<h4 class="wp-block-heading">Collecting into a Map</h4>



<p>Another powerful way to collect data is into a <code>Map</code>. To do this, you can use <code>Collectors.toMap()</code> which requires two functions: one for the key and one for the value.</p>



<div class="wp-block-kevinbatdorf-code-block-pro" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:clamp(14px, .875rem, 21px);font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:clamp(20px, 1.25rem, 30px);--cbp-tab-width:4;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:10px 0px 10px 16px;margin-bottom:-2px;width:100%;text-align:left;background-color:#2f363c;color:#d3d7dd">Java</span><span role="button" tabindex="0" data-code="Stream&lt;String&gt; fruitStream = Stream.of(&quot;apple&quot;, &quot;banana&quot;, &quot;cherry&quot;);
Map&lt;String, Integer&gt; fruitLengthMap = fruitStream.collect(Collectors.toMap(Function.identity(), String::length));" style="color:#e1e4e8;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki github-dark" style="background-color: #24292e" tabindex="0"><code><span class="line"><span style="color: #E1E4E8">Stream&lt;</span><span style="color: #F97583">String</span><span style="color: #E1E4E8">&gt; fruitStream </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> Stream.</span><span style="color: #B392F0">of</span><span style="color: #E1E4E8">(</span><span style="color: #9ECBFF">&quot;apple&quot;</span><span style="color: #E1E4E8">, </span><span style="color: #9ECBFF">&quot;banana&quot;</span><span style="color: #E1E4E8">, </span><span style="color: #9ECBFF">&quot;cherry&quot;</span><span style="color: #E1E4E8">);</span></span>
<span class="line"><span style="color: #E1E4E8">Map&lt;</span><span style="color: #F97583">String</span><span style="color: #E1E4E8">, </span><span style="color: #F97583">Integer</span><span style="color: #E1E4E8">&gt; fruitLengthMap </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> fruitStream.</span><span style="color: #B392F0">collect</span><span style="color: #E1E4E8">(Collectors.</span><span style="color: #B392F0">toMap</span><span style="color: #E1E4E8">(Function.</span><span style="color: #B392F0">identity</span><span style="color: #E1E4E8">(), String</span><span style="color: #F97583">::</span><span style="color: #E1E4E8">length));</span></span></code></pre></div>



<p>In this example, <code>fruitStream</code> contains string elements representing different fruits. We collect these into a <code>Map</code> where the key is the name of the fruit, and the value is the length of its name. Thus, <code>fruitLengthMap</code> will be <code>{apple=5, banana=6, cherry=6}</code>.</p>



<h4 class="wp-block-heading">Aggregation Operations</h4>



<p>Besides collecting elements into a data structure, you can also perform aggregation operations such as summing elements, calculating averages, or finding min/max elements using the <code>collect</code> method.</p>



<p>For example, to find the sum of integers in a Stream:</p>



<div class="wp-block-kevinbatdorf-code-block-pro" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:clamp(14px, .875rem, 21px);font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:clamp(20px, 1.25rem, 30px);--cbp-tab-width:4;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:10px 0px 10px 16px;margin-bottom:-2px;width:100%;text-align:left;background-color:#2f363c;color:#d3d7dd">Java</span><span role="button" tabindex="0" data-code="Stream&lt;Integer&gt; myStream = Stream.of(1, 2, 3, 4, 5);
int sum = myStream.collect(Collectors.summingInt(Integer::intValue));" style="color:#e1e4e8;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki github-dark" style="background-color: #24292e" tabindex="0"><code><span class="line"><span style="color: #E1E4E8">Stream&lt;</span><span style="color: #F97583">Integer</span><span style="color: #E1E4E8">&gt; myStream </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> Stream.</span><span style="color: #B392F0">of</span><span style="color: #E1E4E8">(</span><span style="color: #79B8FF">1</span><span style="color: #E1E4E8">, </span><span style="color: #79B8FF">2</span><span style="color: #E1E4E8">, </span><span style="color: #79B8FF">3</span><span style="color: #E1E4E8">, </span><span style="color: #79B8FF">4</span><span style="color: #E1E4E8">, </span><span style="color: #79B8FF">5</span><span style="color: #E1E4E8">);</span></span>
<span class="line"><span style="color: #F97583">int</span><span style="color: #E1E4E8"> sum </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> myStream.</span><span style="color: #B392F0">collect</span><span style="color: #E1E4E8">(Collectors.</span><span style="color: #B392F0">summingInt</span><span style="color: #E1E4E8">(Integer</span><span style="color: #F97583">::</span><span style="color: #E1E4E8">intValue));</span></span></code></pre></div>



<p>Here, <code>Collectors.summingInt()</code> sums up the integers in the Stream and stores the result in <code>sum</code>.</p>



<h4 class="wp-block-heading">Custom Collector</h4>



<p>You can also create custom collectors by providing supplier, accumulator, and combiner functions to the <code>Collector.of()</code> method, though this is an advanced topic that goes beyond basic usage.</p>



<div class="wp-block-kevinbatdorf-code-block-pro" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:clamp(14px, .875rem, 21px);font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:clamp(20px, 1.25rem, 30px);--cbp-tab-width:4;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:10px 0px 10px 16px;margin-bottom:-2px;width:100%;text-align:left;background-color:#2f363c;color:#d3d7dd">Java</span><span role="button" tabindex="0" data-code="Collector&lt;Integer, ?, LinkedList&lt;Integer&gt;&gt; toLinkedList = Collector.of(
    LinkedList::new,
    LinkedList::add,
    (first, second) -&gt; {
      first.addAll(second);
      return first;
    }
);" style="color:#e1e4e8;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki github-dark" style="background-color: #24292e" tabindex="0"><code><span class="line"><span style="color: #E1E4E8">Collector&lt;</span><span style="color: #F97583">Integer</span><span style="color: #E1E4E8">, </span><span style="color: #F97583">?</span><span style="color: #E1E4E8">, LinkedList&lt;</span><span style="color: #F97583">Integer</span><span style="color: #E1E4E8">&gt;&gt; toLinkedList </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> Collector.</span><span style="color: #B392F0">of</span><span style="color: #E1E4E8">(</span></span>
<span class="line"><span style="color: #E1E4E8">    LinkedList</span><span style="color: #F97583">::new</span><span style="color: #E1E4E8">,</span></span>
<span class="line"><span style="color: #E1E4E8">    LinkedList</span><span style="color: #F97583">::</span><span style="color: #E1E4E8">add,</span></span>
<span class="line"><span style="color: #E1E4E8">    (first, second) </span><span style="color: #F97583">-&gt;</span><span style="color: #E1E4E8"> {</span></span>
<span class="line"><span style="color: #E1E4E8">      first.</span><span style="color: #B392F0">addAll</span><span style="color: #E1E4E8">(second);</span></span>
<span class="line"><span style="color: #E1E4E8">      </span><span style="color: #F97583">return</span><span style="color: #E1E4E8"> first;</span></span>
<span class="line"><span style="color: #E1E4E8">    }</span></span>
<span class="line"><span style="color: #E1E4E8">);</span></span></code></pre></div>



<p>In this case, we&#8217;ve created a custom collector that accumulates the Stream elements into a <code>LinkedList</code>.</p>



<p>Collecting results is a crucial part of working with Streams as it brings the stream pipeline to a definitive end and allows you to convert the Stream back to a more usable data structure.</p>



<h2 class="wp-block-heading">Advanced Uses of Streams</h2>



<h3 class="wp-block-heading">FlatMap</h3>



<p><code>flatMap</code> is a slightly more complex but extremely useful operation that can transform a Stream of collections into a Stream containing all the elements of all the collections.</p>



<div class="wp-block-kevinbatdorf-code-block-pro" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:clamp(14px, .875rem, 21px);font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:clamp(20px, 1.25rem, 30px);--cbp-tab-width:4;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:10px 0px 10px 16px;margin-bottom:-2px;width:100%;text-align:left;background-color:#2f363c;color:#d3d7dd">Java</span><span role="button" tabindex="0" data-code="List&lt;List&lt;String&gt;&gt; nestedList = Arrays.asList(
    Arrays.asList(&quot;apple&quot;, &quot;banana&quot;),
    Arrays.asList(&quot;orange&quot;, &quot;lemon&quot;)
);

Stream&lt;String&gt; flatStream = nestedList.stream().flatMap(Collection::stream);" style="color:#e1e4e8;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki github-dark" style="background-color: #24292e" tabindex="0"><code><span class="line"><span style="color: #E1E4E8">List&lt;List&lt;</span><span style="color: #F97583">String</span><span style="color: #E1E4E8">&gt;&gt; nestedList </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> Arrays.</span><span style="color: #B392F0">asList</span><span style="color: #E1E4E8">(</span></span>
<span class="line"><span style="color: #E1E4E8">    Arrays.</span><span style="color: #B392F0">asList</span><span style="color: #E1E4E8">(</span><span style="color: #9ECBFF">&quot;apple&quot;</span><span style="color: #E1E4E8">, </span><span style="color: #9ECBFF">&quot;banana&quot;</span><span style="color: #E1E4E8">),</span></span>
<span class="line"><span style="color: #E1E4E8">    Arrays.</span><span style="color: #B392F0">asList</span><span style="color: #E1E4E8">(</span><span style="color: #9ECBFF">&quot;orange&quot;</span><span style="color: #E1E4E8">, </span><span style="color: #9ECBFF">&quot;lemon&quot;</span><span style="color: #E1E4E8">)</span></span>
<span class="line"><span style="color: #E1E4E8">);</span></span>
<span class="line"></span>
<span class="line"><span style="color: #E1E4E8">Stream&lt;</span><span style="color: #F97583">String</span><span style="color: #E1E4E8">&gt; flatStream </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> nestedList.</span><span style="color: #B392F0">stream</span><span style="color: #E1E4E8">().</span><span style="color: #B392F0">flatMap</span><span style="color: #E1E4E8">(Collection</span><span style="color: #F97583">::</span><span style="color: #E1E4E8">stream);</span></span></code></pre></div>



<p>This will produce a new Stream consisting of &#8220;apple&#8221;, &#8220;banana&#8221;, &#8220;orange&#8221;, &#8220;lemon&#8221;.</p>



<h3 class="wp-block-heading">Reduce</h3>



<p>The <code>reduce</code> method performs a reduction on the elements of a Stream, using an accumulator function. It can be used to produce a single result from a Stream, like calculating the sum of a list of integers.</p>



<div class="wp-block-kevinbatdorf-code-block-pro" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:clamp(14px, .875rem, 21px);font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:clamp(20px, 1.25rem, 30px);--cbp-tab-width:4;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:10px 0px 10px 16px;margin-bottom:-2px;width:100%;text-align:left;background-color:#2f363c;color:#d3d7dd">Java</span><span role="button" tabindex="0" data-code="Optional&lt;Integer&gt; sum = numbers.stream().reduce((a, b) -&gt; a + b);" style="color:#e1e4e8;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki github-dark" style="background-color: #24292e" tabindex="0"><code><span class="line"><span style="color: #E1E4E8">Optional&lt;</span><span style="color: #F97583">Integer</span><span style="color: #E1E4E8">&gt; sum </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> numbers.</span><span style="color: #B392F0">stream</span><span style="color: #E1E4E8">().</span><span style="color: #B392F0">reduce</span><span style="color: #E1E4E8">((a, b) </span><span style="color: #F97583">-&gt;</span><span style="color: #E1E4E8"> a </span><span style="color: #F97583">+</span><span style="color: #E1E4E8"> b);</span></span></code></pre></div>



<h2 class="wp-block-heading">Comprehensive Code Example with Streams</h2>



<p>To consolidate all the concepts we&#8217;ve covered so far, let&#8217;s dive into a complete Java code example that demonstrates various operations using Streams. This example simulates a simple scenario: We have a list of students, each with a name, age, and grades in multiple subjects. We want to perform a series of operations to filter, transform, and collect data related to these students.</p>



<p>Here&#8217;s the code snippet:</p>



<div class="wp-block-kevinbatdorf-code-block-pro" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:clamp(14px, .875rem, 21px);font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:clamp(20px, 1.25rem, 30px);--cbp-tab-width:4;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:10px 0px 10px 16px;margin-bottom:-2px;width:100%;text-align:left;background-color:#2f363c;color:#d3d7dd">Java</span><span role="button" tabindex="0" data-code="import java.util.*;
import java.util.stream.*;

public class StudentStreamExample {
    public static void main(String[] args) {
        // Step 1: Create a List of Students
        List&lt;Student&gt; students = Arrays.asList(
            new Student(&quot;Alice&quot;, 20, Arrays.asList(90, 85, 92)),
            new Student(&quot;Bob&quot;, 22, Arrays.asList(70, 45, 88)),
            new Student(&quot;Cathy&quot;, 21, Arrays.asList(82, 89, 94)),
            new Student(&quot;David&quot;, 19, Arrays.asList(55, 78, 61)),
            new Student(&quot;Eva&quot;, 20, Arrays.asList(68, 77, 71))
        );

        // Step 2: Filter Students Aged 20 and Above
        List&lt;Student&gt; filteredStudents = students.stream()
				.filter(s -&gt; s.getAge() &gt;= 20)
				.collect(Collectors.toList());

        // Step 3: Transform to Map with Name as Key and Average Grade as Value
        Map&lt;String, Double&gt; studentGradeMap = students.stream()
				.collect(Collectors.toMap(Student::getName,
						s -&gt; s.getGrades().stream()
								.mapToInt(Integer::intValue)
								.average()
								.orElse(0)));

        // Step 4: Find the Student with the Highest Average Grade
        Optional&lt;Student&gt; topStudent = students.stream()
				.max(Comparator.comparing(
						s -&gt; s.getGrades().stream()
								.mapToInt(Integer::intValue)
								.average()
								.orElse(0)));

        // Output the Results
        System.out.println(&quot;Students aged 20 and above: &quot; + filteredStudents);
        System.out.println(&quot;Map of student names and their average grades: &quot; + studentGradeMap);
        System.out.println(&quot;Student with the highest average grade: &quot; + topStudent.orElse(null));
    }
}" style="color:#e1e4e8;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki github-dark" style="background-color: #24292e" tabindex="0"><code><span class="line"><span style="color: #F97583">import</span><span style="color: #E1E4E8"> java.util.</span><span style="color: #79B8FF">*</span><span style="color: #E1E4E8">;</span></span>
<span class="line"><span style="color: #F97583">import</span><span style="color: #E1E4E8"> java.util.stream.</span><span style="color: #79B8FF">*</span><span style="color: #E1E4E8">;</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F97583">public</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">class</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">StudentStreamExample</span><span style="color: #E1E4E8"> {</span></span>
<span class="line"><span style="color: #E1E4E8">    </span><span style="color: #F97583">public</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">static</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">void</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">main</span><span style="color: #E1E4E8">(</span><span style="color: #F97583">String</span><span style="color: #E1E4E8">[] </span><span style="color: #FFAB70">args</span><span style="color: #E1E4E8">) {</span></span>
<span class="line"><span style="color: #E1E4E8">        </span><span style="color: #6A737D">// Step 1: Create a List of Students</span></span>
<span class="line"><span style="color: #E1E4E8">        List&lt;</span><span style="color: #F97583">Student</span><span style="color: #E1E4E8">&gt; students </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> Arrays.</span><span style="color: #B392F0">asList</span><span style="color: #E1E4E8">(</span></span>
<span class="line"><span style="color: #E1E4E8">            </span><span style="color: #F97583">new</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">Student</span><span style="color: #E1E4E8">(</span><span style="color: #9ECBFF">&quot;Alice&quot;</span><span style="color: #E1E4E8">, </span><span style="color: #79B8FF">20</span><span style="color: #E1E4E8">, Arrays.</span><span style="color: #B392F0">asList</span><span style="color: #E1E4E8">(</span><span style="color: #79B8FF">90</span><span style="color: #E1E4E8">, </span><span style="color: #79B8FF">85</span><span style="color: #E1E4E8">, </span><span style="color: #79B8FF">92</span><span style="color: #E1E4E8">)),</span></span>
<span class="line"><span style="color: #E1E4E8">            </span><span style="color: #F97583">new</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">Student</span><span style="color: #E1E4E8">(</span><span style="color: #9ECBFF">&quot;Bob&quot;</span><span style="color: #E1E4E8">, </span><span style="color: #79B8FF">22</span><span style="color: #E1E4E8">, Arrays.</span><span style="color: #B392F0">asList</span><span style="color: #E1E4E8">(</span><span style="color: #79B8FF">70</span><span style="color: #E1E4E8">, </span><span style="color: #79B8FF">45</span><span style="color: #E1E4E8">, </span><span style="color: #79B8FF">88</span><span style="color: #E1E4E8">)),</span></span>
<span class="line"><span style="color: #E1E4E8">            </span><span style="color: #F97583">new</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">Student</span><span style="color: #E1E4E8">(</span><span style="color: #9ECBFF">&quot;Cathy&quot;</span><span style="color: #E1E4E8">, </span><span style="color: #79B8FF">21</span><span style="color: #E1E4E8">, Arrays.</span><span style="color: #B392F0">asList</span><span style="color: #E1E4E8">(</span><span style="color: #79B8FF">82</span><span style="color: #E1E4E8">, </span><span style="color: #79B8FF">89</span><span style="color: #E1E4E8">, </span><span style="color: #79B8FF">94</span><span style="color: #E1E4E8">)),</span></span>
<span class="line"><span style="color: #E1E4E8">            </span><span style="color: #F97583">new</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">Student</span><span style="color: #E1E4E8">(</span><span style="color: #9ECBFF">&quot;David&quot;</span><span style="color: #E1E4E8">, </span><span style="color: #79B8FF">19</span><span style="color: #E1E4E8">, Arrays.</span><span style="color: #B392F0">asList</span><span style="color: #E1E4E8">(</span><span style="color: #79B8FF">55</span><span style="color: #E1E4E8">, </span><span style="color: #79B8FF">78</span><span style="color: #E1E4E8">, </span><span style="color: #79B8FF">61</span><span style="color: #E1E4E8">)),</span></span>
<span class="line"><span style="color: #E1E4E8">            </span><span style="color: #F97583">new</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">Student</span><span style="color: #E1E4E8">(</span><span style="color: #9ECBFF">&quot;Eva&quot;</span><span style="color: #E1E4E8">, </span><span style="color: #79B8FF">20</span><span style="color: #E1E4E8">, Arrays.</span><span style="color: #B392F0">asList</span><span style="color: #E1E4E8">(</span><span style="color: #79B8FF">68</span><span style="color: #E1E4E8">, </span><span style="color: #79B8FF">77</span><span style="color: #E1E4E8">, </span><span style="color: #79B8FF">71</span><span style="color: #E1E4E8">))</span></span>
<span class="line"><span style="color: #E1E4E8">        );</span></span>
<span class="line"></span>
<span class="line"><span style="color: #E1E4E8">        </span><span style="color: #6A737D">// Step 2: Filter Students Aged 20 and Above</span></span>
<span class="line"><span style="color: #E1E4E8">        List&lt;</span><span style="color: #F97583">Student</span><span style="color: #E1E4E8">&gt; filteredStudents </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> students.</span><span style="color: #B392F0">stream</span><span style="color: #E1E4E8">()</span></span>
<span class="line"><span style="color: #E1E4E8">				.</span><span style="color: #B392F0">filter</span><span style="color: #E1E4E8">(s </span><span style="color: #F97583">-&gt;</span><span style="color: #E1E4E8"> s.</span><span style="color: #B392F0">getAge</span><span style="color: #E1E4E8">() </span><span style="color: #F97583">&gt;=</span><span style="color: #E1E4E8"> </span><span style="color: #79B8FF">20</span><span style="color: #E1E4E8">)</span></span>
<span class="line"><span style="color: #E1E4E8">				.</span><span style="color: #B392F0">collect</span><span style="color: #E1E4E8">(Collectors.</span><span style="color: #B392F0">toList</span><span style="color: #E1E4E8">());</span></span>
<span class="line"></span>
<span class="line"><span style="color: #E1E4E8">        </span><span style="color: #6A737D">// Step 3: Transform to Map with Name as Key and Average Grade as Value</span></span>
<span class="line"><span style="color: #E1E4E8">        Map&lt;</span><span style="color: #F97583">String</span><span style="color: #E1E4E8">, </span><span style="color: #F97583">Double</span><span style="color: #E1E4E8">&gt; studentGradeMap </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> students.</span><span style="color: #B392F0">stream</span><span style="color: #E1E4E8">()</span></span>
<span class="line"><span style="color: #E1E4E8">				.</span><span style="color: #B392F0">collect</span><span style="color: #E1E4E8">(Collectors.</span><span style="color: #B392F0">toMap</span><span style="color: #E1E4E8">(Student</span><span style="color: #F97583">::</span><span style="color: #E1E4E8">getName,</span></span>
<span class="line"><span style="color: #E1E4E8">						s </span><span style="color: #F97583">-&gt;</span><span style="color: #E1E4E8"> s.</span><span style="color: #B392F0">getGrades</span><span style="color: #E1E4E8">().</span><span style="color: #B392F0">stream</span><span style="color: #E1E4E8">()</span></span>
<span class="line"><span style="color: #E1E4E8">								.</span><span style="color: #B392F0">mapToInt</span><span style="color: #E1E4E8">(Integer</span><span style="color: #F97583">::</span><span style="color: #E1E4E8">intValue)</span></span>
<span class="line"><span style="color: #E1E4E8">								.</span><span style="color: #B392F0">average</span><span style="color: #E1E4E8">()</span></span>
<span class="line"><span style="color: #E1E4E8">								.</span><span style="color: #B392F0">orElse</span><span style="color: #E1E4E8">(</span><span style="color: #79B8FF">0</span><span style="color: #E1E4E8">)));</span></span>
<span class="line"></span>
<span class="line"><span style="color: #E1E4E8">        </span><span style="color: #6A737D">// Step 4: Find the Student with the Highest Average Grade</span></span>
<span class="line"><span style="color: #E1E4E8">        Optional&lt;</span><span style="color: #F97583">Student</span><span style="color: #E1E4E8">&gt; topStudent </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> students.</span><span style="color: #B392F0">stream</span><span style="color: #E1E4E8">()</span></span>
<span class="line"><span style="color: #E1E4E8">				.</span><span style="color: #B392F0">max</span><span style="color: #E1E4E8">(Comparator.</span><span style="color: #B392F0">comparing</span><span style="color: #E1E4E8">(</span></span>
<span class="line"><span style="color: #E1E4E8">						s </span><span style="color: #F97583">-&gt;</span><span style="color: #E1E4E8"> s.</span><span style="color: #B392F0">getGrades</span><span style="color: #E1E4E8">().</span><span style="color: #B392F0">stream</span><span style="color: #E1E4E8">()</span></span>
<span class="line"><span style="color: #E1E4E8">								.</span><span style="color: #B392F0">mapToInt</span><span style="color: #E1E4E8">(Integer</span><span style="color: #F97583">::</span><span style="color: #E1E4E8">intValue)</span></span>
<span class="line"><span style="color: #E1E4E8">								.</span><span style="color: #B392F0">average</span><span style="color: #E1E4E8">()</span></span>
<span class="line"><span style="color: #E1E4E8">								.</span><span style="color: #B392F0">orElse</span><span style="color: #E1E4E8">(</span><span style="color: #79B8FF">0</span><span style="color: #E1E4E8">)));</span></span>
<span class="line"></span>
<span class="line"><span style="color: #E1E4E8">        </span><span style="color: #6A737D">// Output the Results</span></span>
<span class="line"><span style="color: #E1E4E8">        System.out.</span><span style="color: #B392F0">println</span><span style="color: #E1E4E8">(</span><span style="color: #9ECBFF">&quot;Students aged 20 and above: &quot;</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">+</span><span style="color: #E1E4E8"> filteredStudents);</span></span>
<span class="line"><span style="color: #E1E4E8">        System.out.</span><span style="color: #B392F0">println</span><span style="color: #E1E4E8">(</span><span style="color: #9ECBFF">&quot;Map of student names and their average grades: &quot;</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">+</span><span style="color: #E1E4E8"> studentGradeMap);</span></span>
<span class="line"><span style="color: #E1E4E8">        System.out.</span><span style="color: #B392F0">println</span><span style="color: #E1E4E8">(</span><span style="color: #9ECBFF">&quot;Student with the highest average grade: &quot;</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">+</span><span style="color: #E1E4E8"> topStudent.</span><span style="color: #B392F0">orElse</span><span style="color: #E1E4E8">(</span><span style="color: #79B8FF">null</span><span style="color: #E1E4E8">));</span></span>
<span class="line"><span style="color: #E1E4E8">    }</span></span>
<span class="line"><span style="color: #E1E4E8">}</span></span></code></pre></div>



<h5 class="wp-block-heading">Step 1: Create a List of Students</h5>



<p>First, we create a list of <code>Student</code> objects. Each <code>Student</code> object contains a name, age, and a list of grades. This serves as our raw data that we&#8217;ll manipulate using Streams.</p>



<div class="wp-block-kevinbatdorf-code-block-pro" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:clamp(14px, .875rem, 21px);font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:clamp(20px, 1.25rem, 30px);--cbp-tab-width:4;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:10px 0px 10px 16px;margin-bottom:-2px;width:100%;text-align:left;background-color:#2f363c;color:#d3d7dd">Java</span><span role="button" tabindex="0" data-code="List&lt;Student&gt; students = Arrays.asList(
    new Student(&quot;Alice&quot;, 20, Arrays.asList(90, 85, 92)),
    // ... more students
);" style="color:#e1e4e8;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki github-dark" style="background-color: #24292e" tabindex="0"><code><span class="line"><span style="color: #E1E4E8">List&lt;</span><span style="color: #F97583">Student</span><span style="color: #E1E4E8">&gt; students </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> Arrays.</span><span style="color: #B392F0">asList</span><span style="color: #E1E4E8">(</span></span>
<span class="line"><span style="color: #E1E4E8">    </span><span style="color: #F97583">new</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">Student</span><span style="color: #E1E4E8">(</span><span style="color: #9ECBFF">&quot;Alice&quot;</span><span style="color: #E1E4E8">, </span><span style="color: #79B8FF">20</span><span style="color: #E1E4E8">, Arrays.</span><span style="color: #B392F0">asList</span><span style="color: #E1E4E8">(</span><span style="color: #79B8FF">90</span><span style="color: #E1E4E8">, </span><span style="color: #79B8FF">85</span><span style="color: #E1E4E8">, </span><span style="color: #79B8FF">92</span><span style="color: #E1E4E8">)),</span></span>
<span class="line"><span style="color: #E1E4E8">    </span><span style="color: #6A737D">// ... more students</span></span>
<span class="line"><span style="color: #E1E4E8">);</span></span></code></pre></div>



<h5 class="wp-block-heading">Step 2: Filter Students Aged 20 and Above</h5>



<p>In this step, we use the <code>filter</code> method to find all students who are 20 years old or older.</p>



<div class="wp-block-kevinbatdorf-code-block-pro" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:clamp(14px, .875rem, 21px);font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:clamp(20px, 1.25rem, 30px);--cbp-tab-width:4;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:10px 0px 10px 16px;margin-bottom:-2px;width:100%;text-align:left;background-color:#2f363c;color:#d3d7dd">Java</span><span role="button" tabindex="0" data-code="List&lt;Student&gt; filteredStudents = students.stream()
		.filter(s -&gt; s.getAge() &gt;= 20)
		.collect(Collectors.toList());" style="color:#e1e4e8;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki github-dark" style="background-color: #24292e" tabindex="0"><code><span class="line"><span style="color: #E1E4E8">List&lt;</span><span style="color: #F97583">Student</span><span style="color: #E1E4E8">&gt; filteredStudents </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> students.</span><span style="color: #B392F0">stream</span><span style="color: #E1E4E8">()</span></span>
<span class="line"><span style="color: #E1E4E8">		.</span><span style="color: #B392F0">filter</span><span style="color: #E1E4E8">(s </span><span style="color: #F97583">-&gt;</span><span style="color: #E1E4E8"> s.</span><span style="color: #B392F0">getAge</span><span style="color: #E1E4E8">() </span><span style="color: #F97583">&gt;=</span><span style="color: #E1E4E8"> </span><span style="color: #79B8FF">20</span><span style="color: #E1E4E8">)</span></span>
<span class="line"><span style="color: #E1E4E8">		.</span><span style="color: #B392F0">collect</span><span style="color: #E1E4E8">(Collectors.</span><span style="color: #B392F0">toList</span><span style="color: #E1E4E8">());</span></span></code></pre></div>



<p>We start by converting the list of students into a Stream using the <code>stream()</code> method. Then, we apply the <code>filter</code> operation where the condition is that the student&#8217;s age should be at least 20. Finally, we collect the filtered results back into a list.</p>



<h5 class="wp-block-heading">Step 3: Transform to Map with Name as Key and Average Grade as Value</h5>



<p>Here, we transform our list of students into a map where the key is the student&#8217;s name and the value is their average grade.</p>



<div class="wp-block-kevinbatdorf-code-block-pro" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:clamp(14px, .875rem, 21px);font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:clamp(20px, 1.25rem, 30px);--cbp-tab-width:4;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:10px 0px 10px 16px;margin-bottom:-2px;width:100%;text-align:left;background-color:#2f363c;color:#d3d7dd">Java</span><span role="button" tabindex="0" data-code="Map&lt;String, Double&gt; studentGradeMap = students.stream()
		.collect(Collectors.toMap(Student::getName, 
				s -&gt; s.getGrades().stream()
						.mapToInt(Integer::intValue)
						.average()
						.orElse(0)));" style="color:#e1e4e8;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki github-dark" style="background-color: #24292e" tabindex="0"><code><span class="line"><span style="color: #E1E4E8">Map&lt;</span><span style="color: #F97583">String</span><span style="color: #E1E4E8">, </span><span style="color: #F97583">Double</span><span style="color: #E1E4E8">&gt; studentGradeMap </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> students.</span><span style="color: #B392F0">stream</span><span style="color: #E1E4E8">()</span></span>
<span class="line"><span style="color: #E1E4E8">		.</span><span style="color: #B392F0">collect</span><span style="color: #E1E4E8">(Collectors.</span><span style="color: #B392F0">toMap</span><span style="color: #E1E4E8">(Student</span><span style="color: #F97583">::</span><span style="color: #E1E4E8">getName, </span></span>
<span class="line"><span style="color: #E1E4E8">				s </span><span style="color: #F97583">-&gt;</span><span style="color: #E1E4E8"> s.</span><span style="color: #B392F0">getGrades</span><span style="color: #E1E4E8">().</span><span style="color: #B392F0">stream</span><span style="color: #E1E4E8">()</span></span>
<span class="line"><span style="color: #E1E4E8">						.</span><span style="color: #B392F0">mapToInt</span><span style="color: #E1E4E8">(Integer</span><span style="color: #F97583">::</span><span style="color: #E1E4E8">intValue)</span></span>
<span class="line"><span style="color: #E1E4E8">						.</span><span style="color: #B392F0">average</span><span style="color: #E1E4E8">()</span></span>
<span class="line"><span style="color: #E1E4E8">						.</span><span style="color: #B392F0">orElse</span><span style="color: #E1E4E8">(</span><span style="color: #79B8FF">0</span><span style="color: #E1E4E8">)));</span></span></code></pre></div>



<p>We utilize the <code>collect</code> method with <code>Collectors.toMap</code> to perform this transformation. For each student, we calculate the average grade using another inner Stream operation on the list of grades.</p>



<h5 class="wp-block-heading">Step 4: Find the Student with the Highest Average Grade</h5>



<p>We want to find the student with the highest average grade across all subjects.</p>



<div class="wp-block-kevinbatdorf-code-block-pro" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:clamp(14px, .875rem, 21px);font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:clamp(20px, 1.25rem, 30px);--cbp-tab-width:4;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:10px 0px 10px 16px;margin-bottom:-2px;width:100%;text-align:left;background-color:#2f363c;color:#d3d7dd">Java</span><span role="button" tabindex="0" data-code="Optional&lt;Student&gt; topStudent = students.stream()
		.max(Comparator.comparing(
				s -&gt; s.getGrades().stream()
						.mapToInt(Integer::intValue)
						.average()
						.orElse(0)));" style="color:#e1e4e8;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki github-dark" style="background-color: #24292e" tabindex="0"><code><span class="line"><span style="color: #E1E4E8">Optional&lt;</span><span style="color: #F97583">Student</span><span style="color: #E1E4E8">&gt; topStudent </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> students.</span><span style="color: #B392F0">stream</span><span style="color: #E1E4E8">()</span></span>
<span class="line"><span style="color: #E1E4E8">		.</span><span style="color: #B392F0">max</span><span style="color: #E1E4E8">(Comparator.</span><span style="color: #B392F0">comparing</span><span style="color: #E1E4E8">(</span></span>
<span class="line"><span style="color: #E1E4E8">				s </span><span style="color: #F97583">-&gt;</span><span style="color: #E1E4E8"> s.</span><span style="color: #B392F0">getGrades</span><span style="color: #E1E4E8">().</span><span style="color: #B392F0">stream</span><span style="color: #E1E4E8">()</span></span>
<span class="line"><span style="color: #E1E4E8">						.</span><span style="color: #B392F0">mapToInt</span><span style="color: #E1E4E8">(Integer</span><span style="color: #F97583">::</span><span style="color: #E1E4E8">intValue)</span></span>
<span class="line"><span style="color: #E1E4E8">						.</span><span style="color: #B392F0">average</span><span style="color: #E1E4E8">()</span></span>
<span class="line"><span style="color: #E1E4E8">						.</span><span style="color: #B392F0">orElse</span><span style="color: #E1E4E8">(</span><span style="color: #79B8FF">0</span><span style="color: #E1E4E8">)));</span></span></code></pre></div>



<p>We use the <code>max</code> method, which takes a <code>Comparator</code>. Inside the comparator, we calculate the average grade for each student using Streams, just like in the previous step.</p>



<h5 class="wp-block-heading">Output the Results</h5>



<p>Finally, we output the results of each operation to understand what has been achieved.</p>



<div class="wp-block-kevinbatdorf-code-block-pro" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:clamp(14px, .875rem, 21px);font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:clamp(20px, 1.25rem, 30px);--cbp-tab-width:4;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:10px 0px 10px 16px;margin-bottom:-2px;width:100%;text-align:left;background-color:#2f363c;color:#d3d7dd">Java</span><span role="button" tabindex="0" data-code="System.out.println(&quot;Students aged 20 and above: &quot; + filteredStudents);
// ... other outputs" style="color:#e1e4e8;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki github-dark" style="background-color: #24292e" tabindex="0"><code><span class="line"><span style="color: #E1E4E8">System.out.</span><span style="color: #B392F0">println</span><span style="color: #E1E4E8">(</span><span style="color: #9ECBFF">&quot;Students aged 20 and above: &quot;</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">+</span><span style="color: #E1E4E8"> filteredStudents);</span></span>
<span class="line"><span style="color: #6A737D">// ... other outputs</span></span></code></pre></div>



<p>This example showcases the power and versatility of Java Streams. We filtered a list based on a condition, transformed it into a map with calculated average grades, and even found the student with the highest average—all using declarative, clean, and efficient Stream operations. Understanding these techniques deepens your grasp of Java&#8217;s functional programming capabilities, empowering you to write more robust and maintainable code.</p>



<h2 class="wp-block-heading">Further Reading and Advanced Topics</h2>



<p>If you&#8217;ve found this guide on Java Streams helpful and are interested in diving deeper into this topic, there are several advanced areas and related subjects worth exploring:</p>



<ol class="wp-block-list">
<li><strong>Parallel Streams</strong>: Learn how to leverage multi-core processors to perform Stream operations in parallel for improved performance.</li>



<li><strong>Custom Collectors</strong>: Delve into the creation of custom collectors to perform more complex data gathering and transformation operations.</li>



<li><strong>Lazy Evaluation and Short-Circuiting</strong>: Understand the intricacies of how Streams perform lazy evaluation and how you can use short-circuiting operations like <code>findFirst</code> and <code>anyMatch</code> to improve efficiency.</li>



<li><strong>Stream Concatenation and Merging</strong>: Explore how to concatenate or merge multiple Streams into one, using methods like <code>concat</code> or <code>flatMap</code>.</li>



<li><strong>Exception Handling in Streams</strong>: Investigate the best practices for dealing with exceptions that might occur during Stream operations.</li>



<li><strong>Combining Streams with CompletableFuture</strong>: Learn how to combine Streams with Java&#8217;s CompletableFuture for more complex asynchronous operations.</li>



<li><strong>Infinite Streams</strong>: Understand how to work with infinite Streams and generate sequences on-the-fly using methods like <code>iterate</code> and <code>generate</code>.</li>



<li><strong>Advanced Filtering and Mapping</strong>: Experiment with more advanced operations like <code>partitioningBy</code>, <code>groupingBy</code>, or <code>mapping</code> to perform complex transformations and aggregations.</li>



<li><strong>Stateful Operations</strong>: Get acquainted with stateful operations like <code>distinct</code>, <code>sorted</code>, and <code>limit</code>, and learn when and how to use them effectively.</li>



<li><strong>Integrating with I/O Operations</strong>: Learn how to integrate Java Streams with I/O operations, for example, reading from a file line-by-line and processing it using Streams.</li>



<li><strong>Reactive Programming with Streams</strong>: If you&#8217;re interested in reactive programming, you might want to look into libraries and frameworks that extend the Stream concept, such as RxJava or Project Reactor.</li>



<li><strong>Streams in Java Libraries</strong>: Explore how Streams are used in popular Java libraries and frameworks like Spring and Hibernate to understand real-world applications.</li>
</ol>



<p>By diving into these advanced topics, you&#8217;ll gain a more holistic understanding of Java Streams and how to use them effectively in a wide range of scenarios. Happy learning!</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<p>Streams in Java are a powerful tool for working with sequences of data in a functional programming style. They offer a rich set of operations that can be performed lazily, making them efficient and expressive. From simple tasks like filtering and mapping to more complex operations like flat mapping and reducing, Java Streams provide a wide array of capabilities for modern Java development. Once you get the hang of Streams, they can significantly simplify your code and make it more maintainable and readable.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Unveiling the Power and Versatility of Java Enums</title>
		<link>https://blog.j-dev.app/unveiling-the-power-and-versatility-of-java-enums/</link>
		
		<dc:creator><![CDATA[JuanC]]></dc:creator>
		<pubDate>Mon, 21 Aug 2023 06:12:24 +0000</pubDate>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Enum]]></category>
		<guid isPermaLink="false">https://blog.j-dev.app/?page_id=129</guid>

					<description><![CDATA[Enums, short for &#8220;enumerations,&#8221; are a powerful feature in the Java programming language that allow developers to create a set of named constants. Enums bring clarity, type-safety, and expressiveness to your code by providing a structured way to represent a fixed set of values. In this article, we will explore the intricacies of enums in [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p>Enums, short for &#8220;enumerations,&#8221; are a powerful feature in the Java programming language that allow developers to create a set of named constants. Enums bring clarity, type-safety, and expressiveness to your code by providing a structured way to represent a fixed set of values. In this article, we will explore the intricacies of enums in Java, highlighting their unique characteristics compared to other languages, showcasing practical examples of enums at work, and delving into advanced features that can significantly enhance your programming experience.</p>



<h2 class="wp-block-heading">Defining Enums: A Distinctive Java Feature</h2>



<p>In Java, enums are far more than just named integers; they are robust data types that can hold a predefined set of values. This distinguishes Java&#8217;s enums from those found in other languages like C or C++, where enums are merely symbolic names for integers.</p>



<p>Consider a simple enum representing days of the week:</p>



<div class="wp-block-kevinbatdorf-code-block-pro" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:clamp(14px, .875rem, 21px);font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:clamp(20px, 1.25rem, 30px);--cbp-tab-width:4;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:10px 0px 10px 16px;margin-bottom:-2px;width:100%;text-align:left;background-color:#2f363c;color:#d3d7dd">Java</span><span role="button" tabindex="0" data-code="public enum Day {
    SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}" style="color:#e1e4e8;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki github-dark" style="background-color: #24292e" tabindex="0"><code><span class="line"><span style="color: #F97583">public</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">enum</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">Day</span><span style="color: #E1E4E8"> {</span></span>
<span class="line"><span style="color: #E1E4E8">    </span><span style="color: #79B8FF">SUNDAY</span><span style="color: #E1E4E8">, </span><span style="color: #79B8FF">MONDAY</span><span style="color: #E1E4E8">, </span><span style="color: #79B8FF">TUESDAY</span><span style="color: #E1E4E8">, </span><span style="color: #79B8FF">WEDNESDAY</span><span style="color: #E1E4E8">, </span><span style="color: #79B8FF">THURSDAY</span><span style="color: #E1E4E8">, </span><span style="color: #79B8FF">FRIDAY</span><span style="color: #E1E4E8">, </span><span style="color: #79B8FF">SATURDAY</span></span>
<span class="line"><span style="color: #E1E4E8">}</span></span></code></pre></div>



<p>In this example, the <code>Day</code> enum defines a set of seven constants, one for each day of the week. Unlike in C or C++, these enum values are not implicitly assigned integers, ensuring type-safety and clarity in your code.</p>



<h2 class="wp-block-heading">Basic Usage of Enums: Clarity and Type-Safety</h2>



<p>Enums offer improved code readability by providing meaningful names for values. When using enums, you can avoid the confusion that often arises from using magic numbers or plain strings to represent fixed values.</p>



<p>For instance, instead of writing <code>int day = 1;</code> to represent Monday, you can now use <code>Day day = Day.MONDAY;</code>. This makes your code more self-explanatory and less error-prone.</p>



<h2 class="wp-block-heading">Advanced Features of Enums: Exploring the Possibilities</h2>



<p>Java&#8217;s enums offer more than just named constants. They can have fields, constructors, and methods, making them a versatile tool for modeling complex scenarios. Let&#8217;s dive into some of the advanced features of enums.</p>



<h3 class="wp-block-heading">Enum Constructors and Fields</h3>



<p>Enums can have constructors and fields, allowing you to associate additional data with each enum value. Constructors enable you to initialize enum values with specific attributes. These attributes can be distinct for each enum value, allowing you to encapsulate unique data within each constant.</p>



<p>Consider an enum representing planets:</p>



<div class="wp-block-kevinbatdorf-code-block-pro" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:clamp(14px, .875rem, 21px);font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:clamp(20px, 1.25rem, 30px);--cbp-tab-width:4;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:10px 0px 10px 16px;margin-bottom:-2px;width:100%;text-align:left;background-color:#2f363c;color:#d3d7dd">Java</span><span role="button" tabindex="0" data-code="public enum Planet {
    MERCURY	(3.303e+23, 2.4397e6),
    VENUS	(4.869e+24, 6.0518e6),
    EARTH	(5.976e+24, 6.37814e6),
    // ...

    private final double mass;   // in kilograms
    private final double radius; // in meters

    Planet(double mass, double radius) {
        this.mass = mass;
        this.radius = radius;
    }

    public double getMass() {
        return mass;
    }

    public double getRadius() {
        return radius;
    }
}
" style="color:#e1e4e8;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki github-dark" style="background-color: #24292e" tabindex="0"><code><span class="line"><span style="color: #F97583">public</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">enum</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">Planet</span><span style="color: #E1E4E8"> {</span></span>
<span class="line"><span style="color: #E1E4E8">    </span><span style="color: #79B8FF">MERCURY</span><span style="color: #E1E4E8">	(</span><span style="color: #79B8FF">3.303e+23</span><span style="color: #E1E4E8">, </span><span style="color: #79B8FF">2.4397e6</span><span style="color: #E1E4E8">),</span></span>
<span class="line"><span style="color: #E1E4E8">    </span><span style="color: #79B8FF">VENUS</span><span style="color: #E1E4E8">	(</span><span style="color: #79B8FF">4.869e+24</span><span style="color: #E1E4E8">, </span><span style="color: #79B8FF">6.0518e6</span><span style="color: #E1E4E8">),</span></span>
<span class="line"><span style="color: #E1E4E8">    </span><span style="color: #79B8FF">EARTH</span><span style="color: #E1E4E8">	(</span><span style="color: #79B8FF">5.976e+24</span><span style="color: #E1E4E8">, </span><span style="color: #79B8FF">6.37814e6</span><span style="color: #E1E4E8">),</span></span>
<span class="line"><span style="color: #E1E4E8">    </span><span style="color: #6A737D">// ...</span></span>
<span class="line"></span>
<span class="line"><span style="color: #E1E4E8">    </span><span style="color: #79B8FF">private</span><span style="color: #E1E4E8"> final double mass;   </span><span style="color: #6A737D">// in kilograms</span></span>
<span class="line"><span style="color: #E1E4E8">    </span><span style="color: #F97583">private</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">final</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">double</span><span style="color: #E1E4E8"> radius; </span><span style="color: #6A737D">// in meters</span></span>
<span class="line"></span>
<span class="line"><span style="color: #E1E4E8">    </span><span style="color: #B392F0">Planet</span><span style="color: #E1E4E8">(</span><span style="color: #F97583">double</span><span style="color: #E1E4E8"> </span><span style="color: #FFAB70">mass</span><span style="color: #E1E4E8">, </span><span style="color: #F97583">double</span><span style="color: #E1E4E8"> </span><span style="color: #FFAB70">radius</span><span style="color: #E1E4E8">) {</span></span>
<span class="line"><span style="color: #E1E4E8">        </span><span style="color: #79B8FF">this</span><span style="color: #E1E4E8">.mass </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> mass;</span></span>
<span class="line"><span style="color: #E1E4E8">        </span><span style="color: #79B8FF">this</span><span style="color: #E1E4E8">.radius </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> radius;</span></span>
<span class="line"><span style="color: #E1E4E8">    }</span></span>
<span class="line"></span>
<span class="line"><span style="color: #E1E4E8">    </span><span style="color: #F97583">public</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">double</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">getMass</span><span style="color: #E1E4E8">() {</span></span>
<span class="line"><span style="color: #E1E4E8">        </span><span style="color: #F97583">return</span><span style="color: #E1E4E8"> mass;</span></span>
<span class="line"><span style="color: #E1E4E8">    }</span></span>
<span class="line"></span>
<span class="line"><span style="color: #E1E4E8">    </span><span style="color: #F97583">public</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">double</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">getRadius</span><span style="color: #E1E4E8">() {</span></span>
<span class="line"><span style="color: #E1E4E8">        </span><span style="color: #F97583">return</span><span style="color: #E1E4E8"> radius;</span></span>
<span class="line"><span style="color: #E1E4E8">    }</span></span>
<span class="line"><span style="color: #E1E4E8">}</span></span>
<span class="line"></span></code></pre></div>



<p>In this example, each enum value (planet) is associated with specific mass and radius values. The constructor and fields allow you to encapsulate data relevant to each enum value.</p>



<p>Fields within enums provide a means to store and access additional information related to each constant. These fields are set during enum initialization and can be queried later to retrieve relevant data.</p>



<p>The interplay between constructors and fields within enums can be immensely beneficial in real-world scenarios. Imagine an application that calculates planetary properties. By using the <code>Planet</code> enum with constructors and fields, you can effortlessly access mass and radius data, offering a cohesive and organized approach to data management.</p>



<h3 class="wp-block-heading">Enum Methods and Behaviors</h3>



<p>Enums can have methods, making them behave like classes. You can define behavior specific to each enum value. Let&#8217;s extend the <code>Planet</code> enum with a method for calculating surface gravity:</p>



<div class="wp-block-kevinbatdorf-code-block-pro" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:clamp(14px, .875rem, 21px);font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:clamp(20px, 1.25rem, 30px);--cbp-tab-width:4;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:10px 0px 10px 16px;margin-bottom:-2px;width:100%;text-align:left;background-color:#2f363c;color:#d3d7dd">Java</span><span role="button" tabindex="0" data-code="public enum Planet {
    // ...

    public double surfaceGravity() {
        double G = 6.67300E-11;
        return G * mass / (radius * radius);
    }
}" style="color:#e1e4e8;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki github-dark" style="background-color: #24292e" tabindex="0"><code><span class="line"><span style="color: #F97583">public</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">enum</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">Planet</span><span style="color: #E1E4E8"> {</span></span>
<span class="line"><span style="color: #E1E4E8">    </span><span style="color: #6A737D">// ...</span></span>
<span class="line"></span>
<span class="line"><span style="color: #E1E4E8">    </span><span style="color: #79B8FF">public</span><span style="color: #E1E4E8"> double surfaceGravity() {</span></span>
<span class="line"><span style="color: #E1E4E8">        </span><span style="color: #F97583">double</span><span style="color: #E1E4E8"> G </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> </span><span style="color: #79B8FF">6.67300E-11</span><span style="color: #E1E4E8">;</span></span>
<span class="line"><span style="color: #E1E4E8">        return G * mass / (radius * radius);</span></span>
<span class="line"><span style="color: #E1E4E8">    }</span></span>
<span class="line"><span style="color: #E1E4E8">}</span></span></code></pre></div>



<p>With this method, you can calculate the surface gravity of each planet using the formula provided.</p>



<h2 class="wp-block-heading">Advanced Enum Example</h2>



<p>We&#8217;ll create a program that takes a color from the user, determines its position in the electromagnetic spectrum, and provides information about the type of light associated with that color.</p>



<div class="wp-block-kevinbatdorf-code-block-pro" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:clamp(14px, .875rem, 21px);font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:clamp(20px, 1.25rem, 30px);--cbp-tab-width:4;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:10px 0px 10px 16px;margin-bottom:-2px;width:100%;text-align:left;background-color:#2f363c;color:#d3d7dd">Java</span><span role="button" tabindex="0" data-code="import java.util.Scanner;

public class ColorSpectrumAnalyzer {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print(&quot;Enter a color &quot; + 
                &quot;(RED, ORANGE, YELLOW, GREEN, BLUE, INDIGO, VIOLET, INFRARED, ULTRAVIOLET): &quot;);
        String colorInput = scanner.nextLine().toUpperCase();

        try {
            Color color = Color.valueOf(colorInput);

            System.out.println(&quot;Color: &quot; + color);
            System.out.println(&quot;Wavelength: &quot; + color.getWavelength() + &quot; nm&quot;);
            System.out.println(&quot;Type of Light: &quot; + color.getTypeOfLight());
        } catch (IllegalArgumentException e) {
            System.out.println(&quot;Invalid color entered.&quot;);
        }

        scanner.close();
    }

    enum Color {
        RED			(620, &quot;Visible&quot;),
        ORANGE		(590, &quot;Visible&quot;),
        YELLOW		(570, &quot;Visible&quot;),
        GREEN		(520, &quot;Visible&quot;),
        BLUE		(470, &quot;Visible&quot;),
        INDIGO		(445, &quot;Visible&quot;),
        VIOLET		(400, &quot;Visible&quot;),
        INFRARED	(1000, &quot;Non-visible&quot;),
        ULTRAVIOLET	(10, &quot;Non-visible&quot;);
        
        private final int wavelength; // in nanometers
        private final String typeOfLight;

        Color(int wavelength, String typeOfLight) {
            this.wavelength = wavelength;
            this.typeOfLight = typeOfLight;
        }

        public int getWavelength() {
            return wavelength;
        }

        public String getTypeOfLight() {
            return typeOfLight;
        }
    }
}
" style="color:#e1e4e8;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki github-dark" style="background-color: #24292e" tabindex="0"><code><span class="line"><span style="color: #F97583">import</span><span style="color: #E1E4E8"> java.util.Scanner;</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F97583">public</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">class</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">ColorSpectrumAnalyzer</span><span style="color: #E1E4E8"> {</span></span>
<span class="line"><span style="color: #E1E4E8">    </span><span style="color: #F97583">public</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">static</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">void</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">main</span><span style="color: #E1E4E8">(</span><span style="color: #F97583">String</span><span style="color: #E1E4E8">[] </span><span style="color: #FFAB70">args</span><span style="color: #E1E4E8">) {</span></span>
<span class="line"><span style="color: #E1E4E8">        Scanner scanner </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">new</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">Scanner</span><span style="color: #E1E4E8">(System.in);</span></span>
<span class="line"></span>
<span class="line"><span style="color: #E1E4E8">        System.out.</span><span style="color: #B392F0">print</span><span style="color: #E1E4E8">(</span><span style="color: #9ECBFF">&quot;Enter a color &quot;</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">+</span><span style="color: #E1E4E8"> </span></span>
<span class="line"><span style="color: #E1E4E8">                </span><span style="color: #9ECBFF">&quot;(RED, ORANGE, YELLOW, GREEN, BLUE, INDIGO, VIOLET, INFRARED, ULTRAVIOLET): &quot;</span><span style="color: #E1E4E8">);</span></span>
<span class="line"><span style="color: #E1E4E8">        String colorInput </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> scanner.</span><span style="color: #B392F0">nextLine</span><span style="color: #E1E4E8">().</span><span style="color: #B392F0">toUpperCase</span><span style="color: #E1E4E8">();</span></span>
<span class="line"></span>
<span class="line"><span style="color: #E1E4E8">        </span><span style="color: #F97583">try</span><span style="color: #E1E4E8"> {</span></span>
<span class="line"><span style="color: #E1E4E8">            Color color </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> Color.</span><span style="color: #B392F0">valueOf</span><span style="color: #E1E4E8">(colorInput);</span></span>
<span class="line"></span>
<span class="line"><span style="color: #E1E4E8">            System.out.</span><span style="color: #B392F0">println</span><span style="color: #E1E4E8">(</span><span style="color: #9ECBFF">&quot;Color: &quot;</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">+</span><span style="color: #E1E4E8"> color);</span></span>
<span class="line"><span style="color: #E1E4E8">            System.out.</span><span style="color: #B392F0">println</span><span style="color: #E1E4E8">(</span><span style="color: #9ECBFF">&quot;Wavelength: &quot;</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">+</span><span style="color: #E1E4E8"> color.</span><span style="color: #B392F0">getWavelength</span><span style="color: #E1E4E8">() </span><span style="color: #F97583">+</span><span style="color: #E1E4E8"> </span><span style="color: #9ECBFF">&quot; nm&quot;</span><span style="color: #E1E4E8">);</span></span>
<span class="line"><span style="color: #E1E4E8">            System.out.</span><span style="color: #B392F0">println</span><span style="color: #E1E4E8">(</span><span style="color: #9ECBFF">&quot;Type of Light: &quot;</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">+</span><span style="color: #E1E4E8"> color.</span><span style="color: #B392F0">getTypeOfLight</span><span style="color: #E1E4E8">());</span></span>
<span class="line"><span style="color: #E1E4E8">        } </span><span style="color: #F97583">catch</span><span style="color: #E1E4E8"> (IllegalArgumentException </span><span style="color: #FFAB70">e</span><span style="color: #E1E4E8">) {</span></span>
<span class="line"><span style="color: #E1E4E8">            System.out.</span><span style="color: #B392F0">println</span><span style="color: #E1E4E8">(</span><span style="color: #9ECBFF">&quot;Invalid color entered.&quot;</span><span style="color: #E1E4E8">);</span></span>
<span class="line"><span style="color: #E1E4E8">        }</span></span>
<span class="line"></span>
<span class="line"><span style="color: #E1E4E8">        scanner.</span><span style="color: #B392F0">close</span><span style="color: #E1E4E8">();</span></span>
<span class="line"><span style="color: #E1E4E8">    }</span></span>
<span class="line"></span>
<span class="line"><span style="color: #E1E4E8">    </span><span style="color: #F97583">enum</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">Color</span><span style="color: #E1E4E8"> {</span></span>
<span class="line"><span style="color: #E1E4E8">        </span><span style="color: #79B8FF">RED</span><span style="color: #E1E4E8">			(</span><span style="color: #79B8FF">620</span><span style="color: #E1E4E8">, </span><span style="color: #9ECBFF">&quot;Visible&quot;</span><span style="color: #E1E4E8">),</span></span>
<span class="line"><span style="color: #E1E4E8">        </span><span style="color: #79B8FF">ORANGE</span><span style="color: #E1E4E8">		(</span><span style="color: #79B8FF">590</span><span style="color: #E1E4E8">, </span><span style="color: #9ECBFF">&quot;Visible&quot;</span><span style="color: #E1E4E8">),</span></span>
<span class="line"><span style="color: #E1E4E8">        </span><span style="color: #79B8FF">YELLOW</span><span style="color: #E1E4E8">		(</span><span style="color: #79B8FF">570</span><span style="color: #E1E4E8">, </span><span style="color: #9ECBFF">&quot;Visible&quot;</span><span style="color: #E1E4E8">),</span></span>
<span class="line"><span style="color: #E1E4E8">        </span><span style="color: #79B8FF">GREEN</span><span style="color: #E1E4E8">		(</span><span style="color: #79B8FF">520</span><span style="color: #E1E4E8">, </span><span style="color: #9ECBFF">&quot;Visible&quot;</span><span style="color: #E1E4E8">),</span></span>
<span class="line"><span style="color: #E1E4E8">        </span><span style="color: #79B8FF">BLUE</span><span style="color: #E1E4E8">		(</span><span style="color: #79B8FF">470</span><span style="color: #E1E4E8">, </span><span style="color: #9ECBFF">&quot;Visible&quot;</span><span style="color: #E1E4E8">),</span></span>
<span class="line"><span style="color: #E1E4E8">        </span><span style="color: #79B8FF">INDIGO</span><span style="color: #E1E4E8">		(</span><span style="color: #79B8FF">445</span><span style="color: #E1E4E8">, </span><span style="color: #9ECBFF">&quot;Visible&quot;</span><span style="color: #E1E4E8">),</span></span>
<span class="line"><span style="color: #E1E4E8">        </span><span style="color: #79B8FF">VIOLET</span><span style="color: #E1E4E8">		(</span><span style="color: #79B8FF">400</span><span style="color: #E1E4E8">, </span><span style="color: #9ECBFF">&quot;Visible&quot;</span><span style="color: #E1E4E8">),</span></span>
<span class="line"><span style="color: #E1E4E8">        </span><span style="color: #79B8FF">INFRARED</span><span style="color: #E1E4E8">	(</span><span style="color: #79B8FF">1000</span><span style="color: #E1E4E8">, </span><span style="color: #9ECBFF">&quot;Non-visible&quot;</span><span style="color: #E1E4E8">),</span></span>
<span class="line"><span style="color: #E1E4E8">        </span><span style="color: #79B8FF">ULTRAVIOLET</span><span style="color: #E1E4E8">	(</span><span style="color: #79B8FF">10</span><span style="color: #E1E4E8">, </span><span style="color: #9ECBFF">&quot;Non-visible&quot;</span><span style="color: #E1E4E8">);</span></span>
<span class="line"><span style="color: #E1E4E8">        </span></span>
<span class="line"><span style="color: #E1E4E8">        </span><span style="color: #F97583">private</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">final</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">int</span><span style="color: #E1E4E8"> wavelength; </span><span style="color: #6A737D">// in nanometers</span></span>
<span class="line"><span style="color: #E1E4E8">        </span><span style="color: #F97583">private</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">final</span><span style="color: #E1E4E8"> String typeOfLight;</span></span>
<span class="line"></span>
<span class="line"><span style="color: #E1E4E8">        </span><span style="color: #B392F0">Color</span><span style="color: #E1E4E8">(</span><span style="color: #F97583">int</span><span style="color: #E1E4E8"> </span><span style="color: #FFAB70">wavelength</span><span style="color: #E1E4E8">, String </span><span style="color: #FFAB70">typeOfLight</span><span style="color: #E1E4E8">) {</span></span>
<span class="line"><span style="color: #E1E4E8">            </span><span style="color: #79B8FF">this</span><span style="color: #E1E4E8">.wavelength </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> wavelength;</span></span>
<span class="line"><span style="color: #E1E4E8">            </span><span style="color: #79B8FF">this</span><span style="color: #E1E4E8">.typeOfLight </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> typeOfLight;</span></span>
<span class="line"><span style="color: #E1E4E8">        }</span></span>
<span class="line"></span>
<span class="line"><span style="color: #E1E4E8">        </span><span style="color: #F97583">public</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">int</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">getWavelength</span><span style="color: #E1E4E8">() {</span></span>
<span class="line"><span style="color: #E1E4E8">            </span><span style="color: #F97583">return</span><span style="color: #E1E4E8"> wavelength;</span></span>
<span class="line"><span style="color: #E1E4E8">        }</span></span>
<span class="line"></span>
<span class="line"><span style="color: #E1E4E8">        </span><span style="color: #F97583">public</span><span style="color: #E1E4E8"> String </span><span style="color: #B392F0">getTypeOfLight</span><span style="color: #E1E4E8">() {</span></span>
<span class="line"><span style="color: #E1E4E8">            </span><span style="color: #F97583">return</span><span style="color: #E1E4E8"> typeOfLight;</span></span>
<span class="line"><span style="color: #E1E4E8">        }</span></span>
<span class="line"><span style="color: #E1E4E8">    }</span></span>
<span class="line"><span style="color: #E1E4E8">}</span></span>
<span class="line"></span></code></pre></div>



<p>In this example, the program prompts the user to enter a color from the visible spectrum (ROYGBIV) and then uses the <code>Color</code> enum to retrieve information about the color&#8217;s wavelength and type of light. The program provides an educational insight into the electromagnetic spectrum and the properties of visible light.</p>



<div class="wp-block-kevinbatdorf-code-block-pro" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:clamp(14px, .875rem, 21px);font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:clamp(20px, 1.25rem, 30px);--cbp-tab-width:4;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:10px 0px 10px 16px;margin-bottom:-2px;width:100%;text-align:left;background-color:#2f363c;color:#d3d7dd">Java</span><span role="button" tabindex="0" data-code="enum Color {
    // Enum constants with associated properties
    // RED, ORANGE, ... ULTRAVIOLET
}" style="color:#e1e4e8;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki github-dark" style="background-color: #24292e" tabindex="0"><code><span class="line"><span style="color: #F97583">enum</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">Color</span><span style="color: #E1E4E8"> {</span></span>
<span class="line"><span style="color: #E1E4E8">    </span><span style="color: #6A737D">// Enum constants with associated properties</span></span>
<span class="line"><span style="color: #E1E4E8">    </span><span style="color: #6A737D">// RED, ORANGE, ... ULTRAVIOLET</span></span>
<span class="line"><span style="color: #E1E4E8">}</span></span></code></pre></div>



<p>This part of the code defines the <code>Color</code> enum. Each color is an enum constant and is associated with a wavelength (in nanometers) and a type of light (visible or non-visible).</p>



<div class="wp-block-kevinbatdorf-code-block-pro" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:clamp(14px, .875rem, 21px);font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:clamp(20px, 1.25rem, 30px);--cbp-tab-width:4;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:10px 0px 10px 16px;margin-bottom:-2px;width:100%;text-align:left;background-color:#2f363c;color:#d3d7dd">Java</span><span role="button" tabindex="0" data-code="    RED			(620, &quot;Visible&quot;),
    ORANGE		(590, &quot;Visible&quot;),
    YELLOW		(570, &quot;Visible&quot;),
    GREEN		(520, &quot;Visible&quot;),
    BLUE		(470, &quot;Visible&quot;),
    INDIGO		(445, &quot;Visible&quot;),
    VIOLET		(400, &quot;Visible&quot;),
    INFRARED	(1000, &quot;Non-visible&quot;),
    ULTRAVIOLET	(10, &quot;Non-visible&quot;);" style="color:#e1e4e8;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki github-dark" style="background-color: #24292e" tabindex="0"><code><span class="line"><span style="color: #E1E4E8">    </span><span style="color: #B392F0">RED</span><span style="color: #E1E4E8">			(</span><span style="color: #79B8FF">620</span><span style="color: #E1E4E8">, </span><span style="color: #9ECBFF">&quot;Visible&quot;</span><span style="color: #E1E4E8">),</span></span>
<span class="line"><span style="color: #E1E4E8">    </span><span style="color: #B392F0">ORANGE</span><span style="color: #E1E4E8">		(</span><span style="color: #79B8FF">590</span><span style="color: #E1E4E8">, </span><span style="color: #9ECBFF">&quot;Visible&quot;</span><span style="color: #E1E4E8">),</span></span>
<span class="line"><span style="color: #E1E4E8">    </span><span style="color: #B392F0">YELLOW</span><span style="color: #E1E4E8">		(</span><span style="color: #79B8FF">570</span><span style="color: #E1E4E8">, </span><span style="color: #9ECBFF">&quot;Visible&quot;</span><span style="color: #E1E4E8">),</span></span>
<span class="line"><span style="color: #E1E4E8">    </span><span style="color: #B392F0">GREEN</span><span style="color: #E1E4E8">		(</span><span style="color: #79B8FF">520</span><span style="color: #E1E4E8">, </span><span style="color: #9ECBFF">&quot;Visible&quot;</span><span style="color: #E1E4E8">),</span></span>
<span class="line"><span style="color: #E1E4E8">    </span><span style="color: #B392F0">BLUE</span><span style="color: #E1E4E8">		(</span><span style="color: #79B8FF">470</span><span style="color: #E1E4E8">, </span><span style="color: #9ECBFF">&quot;Visible&quot;</span><span style="color: #E1E4E8">),</span></span>
<span class="line"><span style="color: #E1E4E8">    </span><span style="color: #B392F0">INDIGO</span><span style="color: #E1E4E8">		(</span><span style="color: #79B8FF">445</span><span style="color: #E1E4E8">, </span><span style="color: #9ECBFF">&quot;Visible&quot;</span><span style="color: #E1E4E8">),</span></span>
<span class="line"><span style="color: #E1E4E8">    </span><span style="color: #B392F0">VIOLET</span><span style="color: #E1E4E8">		(</span><span style="color: #79B8FF">400</span><span style="color: #E1E4E8">, </span><span style="color: #9ECBFF">&quot;Visible&quot;</span><span style="color: #E1E4E8">),</span></span>
<span class="line"><span style="color: #E1E4E8">    </span><span style="color: #B392F0">INFRARED</span><span style="color: #E1E4E8">	(</span><span style="color: #79B8FF">1000</span><span style="color: #E1E4E8">, </span><span style="color: #9ECBFF">&quot;Non-visible&quot;</span><span style="color: #E1E4E8">),</span></span>
<span class="line"><span style="color: #E1E4E8">    </span><span style="color: #B392F0">ULTRAVIOLET</span><span style="color: #E1E4E8">	(</span><span style="color: #79B8FF">10</span><span style="color: #E1E4E8">, </span><span style="color: #9ECBFF">&quot;Non-visible&quot;</span><span style="color: #E1E4E8">);</span></span></code></pre></div>



<p>Each enum constant is followed by a set of parentheses, representing the constructor of the enum. Each constant is associated with a wavelength value and a type of light. This data is used to provide information about each color.</p>



<div class="wp-block-kevinbatdorf-code-block-pro" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:clamp(14px, .875rem, 21px);font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:clamp(20px, 1.25rem, 30px);--cbp-tab-width:4;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:10px 0px 10px 16px;margin-bottom:-2px;width:100%;text-align:left;background-color:#2f363c;color:#d3d7dd">Java</span><span role="button" tabindex="0" data-code="    private final int wavelength; // in nanometers
    private final String typeOfLight;

    Color(int wavelength, String typeOfLight) {
        this.wavelength = wavelength;
        this.typeOfLight = typeOfLight;
    }

    public int getWavelength() {
        return wavelength;
    }

    public String getTypeOfLight() {
        return typeOfLight;
    }" style="color:#e1e4e8;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki github-dark" style="background-color: #24292e" tabindex="0"><code><span class="line"><span style="color: #E1E4E8">    </span><span style="color: #F97583">private</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">final</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">int</span><span style="color: #E1E4E8"> wavelength; </span><span style="color: #6A737D">// in nanometers</span></span>
<span class="line"><span style="color: #E1E4E8">    </span><span style="color: #F97583">private</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">final</span><span style="color: #E1E4E8"> String typeOfLight;</span></span>
<span class="line"></span>
<span class="line"><span style="color: #E1E4E8">    </span><span style="color: #B392F0">Color</span><span style="color: #E1E4E8">(</span><span style="color: #F97583">int</span><span style="color: #E1E4E8"> wavelength, String typeOfLight) {</span></span>
<span class="line"><span style="color: #E1E4E8">        </span><span style="color: #79B8FF">this</span><span style="color: #E1E4E8">.wavelength </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> wavelength;</span></span>
<span class="line"><span style="color: #E1E4E8">        </span><span style="color: #79B8FF">this</span><span style="color: #E1E4E8">.typeOfLight </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> typeOfLight;</span></span>
<span class="line"><span style="color: #E1E4E8">    }</span></span>
<span class="line"></span>
<span class="line"><span style="color: #E1E4E8">    </span><span style="color: #F97583">public</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">int</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">getWavelength</span><span style="color: #E1E4E8">() {</span></span>
<span class="line"><span style="color: #E1E4E8">        </span><span style="color: #F97583">return</span><span style="color: #E1E4E8"> wavelength;</span></span>
<span class="line"><span style="color: #E1E4E8">    }</span></span>
<span class="line"></span>
<span class="line"><span style="color: #E1E4E8">    </span><span style="color: #F97583">public</span><span style="color: #E1E4E8"> String </span><span style="color: #B392F0">getTypeOfLight</span><span style="color: #E1E4E8">() {</span></span>
<span class="line"><span style="color: #E1E4E8">        </span><span style="color: #F97583">return</span><span style="color: #E1E4E8"> typeOfLight;</span></span>
<span class="line"><span style="color: #E1E4E8">    }</span></span></code></pre></div>



<p>Each enum constant has a constructor that sets its wavelength and type of light. The <code>getWavelength()</code> and <code>getTypeOfLight()</code> methods allow you to access these properties for each color.</p>



<p>In summary, this Java program demonstrates the use of an enum to represent colors and provides information about the entered color&#8217;s wavelength and type of light. It also handles invalid color inputs using a try-catch block.</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<p>Enums in Java are a versatile and powerful construct that go beyond simple named constants. They provide type-safety, clarity, and meaningful structure to your code. With advanced features like constructors, fields, and methods, enums can be used to model complex scenarios effectively.</p>



<p>In this article, we&#8217;ve covered the basics of enums, highlighted their unique aspects in Java, demonstrated their simple and advanced usage, and provided a comprehensive example that showcases their potential. By understanding and leveraging the capabilities of enums, you can write more maintainable, expressive, and organized code in your Java projects.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Lambda Expressions in Java: A Deep Dive into Functional Programming</title>
		<link>https://blog.j-dev.app/lambda-expressions-in-java/</link>
		
		<dc:creator><![CDATA[JuanC]]></dc:creator>
		<pubDate>Sat, 12 Aug 2023 07:15:10 +0000</pubDate>
				<category><![CDATA[Functional programming]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Lambda]]></category>
		<guid isPermaLink="false">https://blog.j-dev.app/?page_id=91</guid>

					<description><![CDATA[Lambda expressions have transformed the Java programming landscape, introducing functional programming capabilities that promote concise and expressive code. In this comprehensive guide, we’ll embark on a detailed exploration of lambda expressions in Java. We’ll delve into their fundamental nature, the intricate relationship they share with interfaces, and the main functional interfaces provided by Java. Throughout [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p>Lambda expressions have transformed the Java programming landscape, introducing functional programming capabilities that promote concise and expressive code. In this comprehensive guide, we’ll embark on a detailed exploration of lambda expressions in Java. We’ll delve into their fundamental nature, the intricate relationship they share with interfaces, and the main functional interfaces provided by Java. Throughout this article, we’ll use extensive code examples, providing a thorough understanding of the topic. Whether you’re new to Java or an experienced developer, this guide will enrich your knowledge of lambda expressions.</p>



<h2 class="wp-block-heading">Understanding Lambda Expressions</h2>



<p>Lambda expressions might seem mysterious when you first encounter them, but they can be understood quite simply: A lambda expression is essentially an anonymous function. In simpler terms, it&#8217;s a chunk of code you can use without having to declare it within a traditional Java class or method. Think of it as a compact, inline function that you can pass around as a variable or use as a parameter for other methods.</p>



<h3 class="wp-block-heading">What Makes a Lambda Expression &#8220;Anonymous&#8221;?</h3>



<p>When we talk about anonymity in this context, we mean that the function does not have a name; it&#8217;s not declared like typical methods with a <code>public</code>, <code>private</code>, or <code>protected</code> keyword, and it doesn&#8217;t have a return type specified. Instead, all of this information is implied by the context in which the lambda is used.</p>



<h3 class="wp-block-heading">The Power of Lambda: Functional Programming in Java</h3>



<p>Lambda expressions are rooted in the principles of functional programming, a paradigm that treats computation as the evaluation of mathematical functions and avoids changing state or mutable data. By using lambdas, Java allows you to adopt functional styles of programming, resulting in code that is often more concise and easier to test and debug.</p>



<p>Consider the following snippet of code:</p>



<div class="wp-block-kevinbatdorf-code-block-pro" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:clamp(14px, .875rem, 21px);font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:clamp(20px, 1.25rem, 30px);--cbp-tab-width:4;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:10px 0px 10px 16px;margin-bottom:-2px;width:100%;text-align:left;background-color:#2f363c;color:#d3d7dd">Java</span><span role="button" tabindex="0" data-code="Runnable runnable = () -&gt; System.out.println(&quot;Hello, Lambda!&quot;);" style="color:#e1e4e8;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki github-dark" style="background-color: #24292e" tabindex="0"><code><span class="line"><span style="color: #E1E4E8">Runnable runnable </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> () </span><span style="color: #F97583">-&gt;</span><span style="color: #E1E4E8"> System.out.</span><span style="color: #B392F0">println</span><span style="color: #E1E4E8">(</span><span style="color: #9ECBFF">&quot;Hello, Lambda!&quot;</span><span style="color: #E1E4E8">);</span></span></code></pre></div>



<p>Let&#8217;s break this down:</p>



<ul class="wp-block-list">
<li><code>Runnable</code>: This is an interface in Java with a single abstract method called <code>run()</code> that takes no arguments and returns no value (<code>void</code>).</li>



<li><code>runnable</code>: This is a variable that holds our lambda expression, which is a Runnable object.</li>



<li><code>() -&gt;</code>: The empty parentheses indicate that this lambda expression takes no parameters. If you were to require parameters, they would go inside these parentheses.</li>



<li><code>System.out.println("Hello, Lambda!")</code>: This is the body of the lambda expression. It represents the code that will be executed when the <code>run()</code> method of the <code>Runnable</code> interface is called.</li>
</ul>



<h3 class="wp-block-heading">Comparing With Anonymous Inner Classes</h3>



<p>Before lambdas were introduced, you&#8217;d have to do something like this to achieve the same effect:</p>



<div class="wp-block-kevinbatdorf-code-block-pro" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:clamp(14px, .875rem, 21px);font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:clamp(20px, 1.25rem, 30px);--cbp-tab-width:4;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:10px 0px 10px 16px;margin-bottom:-2px;width:100%;text-align:left;background-color:#2f363c;color:#d3d7dd">Java</span><span role="button" tabindex="0" data-code="Runnable runnable = new Runnable() {
    @Override
    public void run() {
        System.out.println(&quot;Hello, Non-Lambda!&quot;);
    }
};" style="color:#e1e4e8;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki github-dark" style="background-color: #24292e" tabindex="0"><code><span class="line"><span style="color: #E1E4E8">Runnable runnable </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">new</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">Runnable</span><span style="color: #E1E4E8">() {</span></span>
<span class="line"><span style="color: #E1E4E8">    @</span><span style="color: #F97583">Override</span></span>
<span class="line"><span style="color: #E1E4E8">    </span><span style="color: #F97583">public</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">void</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">run</span><span style="color: #E1E4E8">() {</span></span>
<span class="line"><span style="color: #E1E4E8">        System.out.</span><span style="color: #B392F0">println</span><span style="color: #E1E4E8">(</span><span style="color: #9ECBFF">&quot;Hello, Non-Lambda!&quot;</span><span style="color: #E1E4E8">);</span></span>
<span class="line"><span style="color: #E1E4E8">    }</span></span>
<span class="line"><span style="color: #E1E4E8">};</span></span></code></pre></div>



<p>That&#8217;s a lot of boilerplate code for a simple operation! With lambdas, you can do the same thing but with much less code, making it easier to read and understand.</p>



<h3 class="wp-block-heading">How to Use Lambdas in Your Code</h3>



<p>Lambda expressions are first-class citizens in Java. This means you can:</p>



<ul class="wp-block-list">
<li>Store them in variables</li>



<li>Pass them as parameters to other methods</li>



<li>Return them as values from other methods</li>



<li>Use them in array initializers and other data structures like Lists and Maps</li>
</ul>



<p>They&#8217;re incredibly versatile and useful for a variety of tasks, from simple event listeners in graphical user interfaces to complex operations in concurrent programming.</p>



<h2 class="wp-block-heading">The Role of Functional Interfaces</h2>



<p>Lambda expressions are intrinsically tied to <a href="https://docs.oracle.com/javase/specs/jls/se17/html/jls-9.html#jls-9.8" target="_blank" rel="noreferrer noopener">functional interfaces</a>. A functional interface is an interface with exactly one abstract method. Functional interfaces serve as the foundation for lambda expressions, defining the shape of the functions these expressions can represent.</p>



<p>A <strong>functional interface</strong> is characterized by its single abstract method, which signifies the primary action the interface represents. The implementation of the <code>Runnable</code> interface shown above, for example, defines the <code>run()</code> method for executing code in a new thread. </p>



<p>The <code>Runnable</code> interface, with its single abstract method <code>run()</code>, serves as the target for the lambda expression. In this way, by specifying a single method, functional interfaces ensure that lambda expressions are used to express specific actions, maintaining clarity and preventing ambiguity.</p>



<p>To understand this better, consider now the <code>Comparator</code> interface, which provides a method for comparing two objects:</p>



<div class="wp-block-kevinbatdorf-code-block-pro" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:clamp(14px, .875rem, 21px);font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:clamp(20px, 1.25rem, 30px);--cbp-tab-width:4;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:10px 0px 10px 16px;margin-bottom:-2px;width:100%;text-align:left;background-color:#2f363c;color:#d3d7dd">Java</span><span role="button" tabindex="0" data-code="@FunctionalInterface
public interface Comparator&lt;T&gt; {
    int compare(T o1, T o2);
}" style="color:#e1e4e8;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki github-dark" style="background-color: #24292e" tabindex="0"><code><span class="line"><span style="color: #E1E4E8">@</span><span style="color: #F97583">FunctionalInterface</span></span>
<span class="line"><span style="color: #F97583">public</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">interface</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">Comparator</span><span style="color: #E1E4E8">&lt;</span><span style="color: #F97583">T</span><span style="color: #E1E4E8">&gt; {</span></span>
<span class="line"><span style="color: #E1E4E8">    </span><span style="color: #F97583">int</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">compare</span><span style="color: #E1E4E8">(T </span><span style="color: #FFAB70">o1</span><span style="color: #E1E4E8">, T </span><span style="color: #FFAB70">o2</span><span style="color: #E1E4E8">);</span></span>
<span class="line"><span style="color: #E1E4E8">}</span></span></code></pre></div>



<p>In this example, the <code>Comparator</code> interface declares the <code>compare(T o1, T o2)</code> method. The annotation <code>@FunctionalInterface</code> explicitly marks it as a functional interface, signaling to developers that this interface is intended for use with lambda expressions.</p>



<p>Lambda expressions excel in simplifying code by providing a concise way to implement functional interfaces. Instead of creating verbose anonymous inner classes, you can define lambda expressions inline, reducing boilerplate code.</p>



<p>Let&#8217;s consider the <code>Comparator</code> example again. Traditionally, you might implement it with an anonymous inner class like this:</p>



<div class="wp-block-kevinbatdorf-code-block-pro" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:clamp(14px, .875rem, 21px);font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:clamp(20px, 1.25rem, 30px);--cbp-tab-width:4;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:10px 0px 10px 16px;margin-bottom:-2px;width:100%;text-align:left;background-color:#2f363c;color:#d3d7dd">Java</span><span role="button" tabindex="0" data-code="Comparator&lt;Integer&gt; comparator = new Comparator&lt;Integer&gt;() {
    @Override
    public int compare(Integer o1, Integer o2) {
        return o1.compareTo(o2);
    }
};" style="color:#e1e4e8;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki github-dark" style="background-color: #24292e" tabindex="0"><code><span class="line"><span style="color: #E1E4E8">Comparator&lt;</span><span style="color: #F97583">Integer</span><span style="color: #E1E4E8">&gt; comparator </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">new</span><span style="color: #E1E4E8"> Comparator&lt;</span><span style="color: #F97583">Integer</span><span style="color: #E1E4E8">&gt;() {</span></span>
<span class="line"><span style="color: #E1E4E8">    @</span><span style="color: #F97583">Override</span></span>
<span class="line"><span style="color: #E1E4E8">    </span><span style="color: #F97583">public</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">int</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">compare</span><span style="color: #E1E4E8">(Integer </span><span style="color: #FFAB70">o1</span><span style="color: #E1E4E8">, Integer </span><span style="color: #FFAB70">o2</span><span style="color: #E1E4E8">) {</span></span>
<span class="line"><span style="color: #E1E4E8">        </span><span style="color: #F97583">return</span><span style="color: #E1E4E8"> o1.</span><span style="color: #B392F0">compareTo</span><span style="color: #E1E4E8">(o2);</span></span>
<span class="line"><span style="color: #E1E4E8">    }</span></span>
<span class="line"><span style="color: #E1E4E8">};</span></span></code></pre></div>



<p>However, using a lambda expression, you can achieve the same functionality with significantly less code:</p>



<div class="wp-block-kevinbatdorf-code-block-pro" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:clamp(14px, .875rem, 21px);font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:clamp(20px, 1.25rem, 30px);--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:10px 0px 10px 16px;margin-bottom:-2px;width:100%;text-align:left;background-color:#2f363c;color:#d3d7dd">Java</span><span role="button" tabindex="0" data-code="Comparator&lt;Integer&gt; comparator = (o1, o2) -&gt; o1.compareTo(o2);" style="color:#e1e4e8;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki github-dark" style="background-color: #24292e" tabindex="0"><code><span class="line"><span style="color: #E1E4E8">Comparator&lt;</span><span style="color: #F97583">Integer</span><span style="color: #E1E4E8">&gt; comparator </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> (o1, o2) </span><span style="color: #F97583">-&gt;</span><span style="color: #E1E4E8"> o1.</span><span style="color: #B392F0">compareTo</span><span style="color: #E1E4E8">(o2);</span></span></code></pre></div>



<h2 class="wp-block-heading">Syntax of a Lambda Expression</h2>



<p>The syntax of a lambda expression is composed of three main parts:</p>



<ol class="wp-block-list">
<li><strong>Parameters</strong>: Enclosed within parentheses, lambda parameters specify the inputs the lambda expression accepts. In this case, <code>(o1, o2)</code> represents the two integer parameters passed to the <code>compare</code> method. The parentheses around parameters are not always necessary; for example, if there&#8217;s only one parameter, you can omit the parentheses: <code>x -&gt; x * x</code>. You can omit the type of the parameters if they can be inferred by the compiler. However, you can explicitly write the parameters type if necessary.</li>



<li><strong>Arrow Token</strong>: The arrow token <code>-&gt;</code> separates the parameters from the body of the lambda expression. It signifies the transition from parameter declaration to the implementation of the method.</li>



<li><strong>Body</strong>: The body of the lambda expression contains the code that performs the desired action. Here, <code>o1.compareTo(o2)</code> returns the result of comparing the two integers. If the body contains only one statement, you can omit the curly braces. However, if you need more than one line of code, you must use curly braces and explicitly use the <code>return</code> keyword if the method returns a value.</li>
</ol>



<p>Understanding when to use parentheses, curly braces, and the <code>return</code> keyword is key to writing correct and readable lambda expressions. These considerations ensure that your lambda expressions are concise while still adhering to the structure and conventions of the Java language.</p>



<p>Incorporating lambda expressions simplifies the implementation of functional interfaces, making your codebase cleaner, more manageable, and better aligned with functional programming paradigms.</p>



<p>It’s important to note that Java has a range of built-in functional interfaces, each catering to specific functional programming needs.</p>



<h2 class="wp-block-heading">Dive into Java&#8217;s Functional Interfaces</h2>



<p>Java offers several essential functional interfaces, each tailored for a particular use case, that can be used with lambda expressions:</p>



<ol class="wp-block-list">
<li><strong>Consumer&lt;T&gt;</strong>: This interface takes an argument of type T, performs an operation on it, and doesn’t return a result. It’s ideal for scenarios where you need to apply a function to a value.</li>
</ol>



<p>Example:</p>



<div class="wp-block-kevinbatdorf-code-block-pro" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:clamp(14px, .875rem, 21px);font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:clamp(20px, 1.25rem, 30px);--cbp-tab-width:4;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:10px 0px 10px 16px;margin-bottom:-2px;width:100%;text-align:left;background-color:#2f363c;color:#d3d7dd">Java</span><span role="button" tabindex="0" data-code="Consumer&lt;String&gt; printUpperCase = (str) -&gt; System.out.println(str.toUpperCase());" style="color:#e1e4e8;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki github-dark" style="background-color: #24292e" tabindex="0"><code><span class="line"><span style="color: #E1E4E8">Consumer&lt;</span><span style="color: #F97583">String</span><span style="color: #E1E4E8">&gt; printUpperCase </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> (str) </span><span style="color: #F97583">-&gt;</span><span style="color: #E1E4E8"> System.out.</span><span style="color: #B392F0">println</span><span style="color: #E1E4E8">(str.</span><span style="color: #B392F0">toUpperCase</span><span style="color: #E1E4E8">());</span></span></code></pre></div>



<ol class="wp-block-list" start="2">
<li><strong>Predicate&lt;T&gt;</strong>: Predicates evaluate a condition on a single argument of type T and return a boolean. It’s widely used for filtering and testing elements.</li>
</ol>



<p>Example:</p>



<div class="wp-block-kevinbatdorf-code-block-pro" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:clamp(14px, .875rem, 21px);font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:clamp(20px, 1.25rem, 30px);--cbp-tab-width:4;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:10px 0px 10px 16px;margin-bottom:-2px;width:100%;text-align:left;background-color:#2f363c;color:#d3d7dd">Java</span><span role="button" tabindex="0" data-code="Predicate&lt;Integer&gt; isEven = (num) -&gt; num % 2 == 0;" style="color:#e1e4e8;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki github-dark" style="background-color: #24292e" tabindex="0"><code><span class="line"><span style="color: #E1E4E8">Predicate&lt;</span><span style="color: #F97583">Integer</span><span style="color: #E1E4E8">&gt; isEven </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> (num) </span><span style="color: #F97583">-&gt;</span><span style="color: #E1E4E8"> num </span><span style="color: #F97583">%</span><span style="color: #E1E4E8"> </span><span style="color: #79B8FF">2</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">==</span><span style="color: #E1E4E8"> </span><span style="color: #79B8FF">0</span><span style="color: #E1E4E8">;</span></span></code></pre></div>



<ol class="wp-block-list" start="3">
<li><strong>Function&lt;T, R&gt;</strong>: Functions accept an argument of type T and produce a result of type R. It’s the go-to interface for mapping one value to another.</li>
</ol>



<p>Example:</p>



<div class="wp-block-kevinbatdorf-code-block-pro" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:clamp(14px, .875rem, 21px);font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:clamp(20px, 1.25rem, 30px);--cbp-tab-width:4;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:10px 0px 10px 16px;margin-bottom:-2px;width:100%;text-align:left;background-color:#2f363c;color:#d3d7dd">Java</span><span role="button" tabindex="0" data-code="Function&lt;Integer, String&gt; intToString = (num) -&gt; Integer.toString(num);" style="color:#e1e4e8;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki github-dark" style="background-color: #24292e" tabindex="0"><code><span class="line"><span style="color: #E1E4E8">Function&lt;</span><span style="color: #F97583">Integer</span><span style="color: #E1E4E8">, </span><span style="color: #F97583">String</span><span style="color: #E1E4E8">&gt; intToString </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> (num) </span><span style="color: #F97583">-&gt;</span><span style="color: #E1E4E8"> Integer.</span><span style="color: #B392F0">toString</span><span style="color: #E1E4E8">(num);</span></span></code></pre></div>



<ol class="wp-block-list" start="4">
<li><strong>Supplier&lt;T&gt;</strong>: Suppliers produce values without taking any input. They’re useful when you need to generate values lazily.</li>
</ol>



<p>Example:</p>



<div class="wp-block-kevinbatdorf-code-block-pro" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:clamp(14px, .875rem, 21px);font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:clamp(20px, 1.25rem, 30px);--cbp-tab-width:4;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:10px 0px 10px 16px;margin-bottom:-2px;width:100%;text-align:left;background-color:#2f363c;color:#d3d7dd">Java</span><span role="button" tabindex="0" data-code="Supplier&lt;Double&gt; randomDouble = () -&gt; Math.random();" style="color:#e1e4e8;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki github-dark" style="background-color: #24292e" tabindex="0"><code><span class="line"><span style="color: #E1E4E8">Supplier&lt;</span><span style="color: #F97583">Double</span><span style="color: #E1E4E8">&gt; randomDouble </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> () </span><span style="color: #F97583">-&gt;</span><span style="color: #E1E4E8"> Math.</span><span style="color: #B392F0">random</span><span style="color: #E1E4E8">();</span></span></code></pre></div>



<h2 class="wp-block-heading">A Practical Illustration: Adaptable Number Processing</h2>



<p>Let’s delve into a practical scenario where lambda expressions shine: adapting behavior using lambda expressions. Imagine you have a list of integers, and you want to process each number differently based on the operation provided. We’ll define a method that accepts a lambda expression as a parameter, allowing us to change the processing behavior flexibly.</p>



<div class="wp-block-kevinbatdorf-code-block-pro" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:clamp(14px, .875rem, 21px);font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:clamp(20px, 1.25rem, 30px);--cbp-tab-width:4;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:10px 0px 10px 16px;margin-bottom:-2px;width:100%;text-align:left;background-color:#2f363c;color:#d3d7dd">Java</span><span role="button" tabindex="0" data-code="public class LambdaAdaptabilityExample {
    interface NumberProcessor {
        void process(int number);
    }

    static void processNumbers(List&lt;Integer&gt; numbers, NumberProcessor processor) {
        for (int num : numbers) {
            processor.process(num);
        }
    }

    public static void main(String[] args) {
        List&lt;Integer&gt; numbers = Arrays.asList(1, 2, 3, 4, 5);

        // Define different processing behaviors using lambda expressions
        NumberProcessor squareProcessor = (num) -&gt; {
            int result = num * num;
            System.out.println(&quot;Square of &quot; + num + &quot;: &quot; + result);
        };

        NumberProcessor cubeProcessor = (num) -&gt; {
            int result = num * num * num;
            System.out.println(&quot;Cube of &quot; + num + &quot;: &quot; + result);
        };

        // Process the numbers with different behaviors
        System.out.println(&quot;Processing with squareProcessor:&quot;);
        processNumbers(numbers, squareProcessor);

        System.out.println(&quot;Processing with cubeProcessor:&quot;);
        processNumbers(numbers, cubeProcessor);
    }
}" style="color:#e1e4e8;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki github-dark" style="background-color: #24292e" tabindex="0"><code><span class="line"><span style="color: #F97583">public</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">class</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">LambdaAdaptabilityExample</span><span style="color: #E1E4E8"> {</span></span>
<span class="line"><span style="color: #E1E4E8">    </span><span style="color: #F97583">interface</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">NumberProcessor</span><span style="color: #E1E4E8"> {</span></span>
<span class="line"><span style="color: #E1E4E8">        </span><span style="color: #F97583">void</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">process</span><span style="color: #E1E4E8">(</span><span style="color: #F97583">int</span><span style="color: #E1E4E8"> </span><span style="color: #FFAB70">number</span><span style="color: #E1E4E8">);</span></span>
<span class="line"><span style="color: #E1E4E8">    }</span></span>
<span class="line"></span>
<span class="line"><span style="color: #E1E4E8">    </span><span style="color: #F97583">static</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">void</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">processNumbers</span><span style="color: #E1E4E8">(List&lt;</span><span style="color: #F97583">Integer</span><span style="color: #E1E4E8">&gt; </span><span style="color: #FFAB70">numbers</span><span style="color: #E1E4E8">, NumberProcessor </span><span style="color: #FFAB70">processor</span><span style="color: #E1E4E8">) {</span></span>
<span class="line"><span style="color: #E1E4E8">        </span><span style="color: #F97583">for</span><span style="color: #E1E4E8"> (</span><span style="color: #F97583">int</span><span style="color: #E1E4E8"> num </span><span style="color: #F97583">:</span><span style="color: #E1E4E8"> numbers) {</span></span>
<span class="line"><span style="color: #E1E4E8">            processor.</span><span style="color: #B392F0">process</span><span style="color: #E1E4E8">(num);</span></span>
<span class="line"><span style="color: #E1E4E8">        }</span></span>
<span class="line"><span style="color: #E1E4E8">    }</span></span>
<span class="line"></span>
<span class="line"><span style="color: #E1E4E8">    </span><span style="color: #F97583">public</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">static</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">void</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">main</span><span style="color: #E1E4E8">(</span><span style="color: #F97583">String</span><span style="color: #E1E4E8">[] </span><span style="color: #FFAB70">args</span><span style="color: #E1E4E8">) {</span></span>
<span class="line"><span style="color: #E1E4E8">        List&lt;</span><span style="color: #F97583">Integer</span><span style="color: #E1E4E8">&gt; numbers </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> Arrays.</span><span style="color: #B392F0">asList</span><span style="color: #E1E4E8">(</span><span style="color: #79B8FF">1</span><span style="color: #E1E4E8">, </span><span style="color: #79B8FF">2</span><span style="color: #E1E4E8">, </span><span style="color: #79B8FF">3</span><span style="color: #E1E4E8">, </span><span style="color: #79B8FF">4</span><span style="color: #E1E4E8">, </span><span style="color: #79B8FF">5</span><span style="color: #E1E4E8">);</span></span>
<span class="line"></span>
<span class="line"><span style="color: #E1E4E8">        </span><span style="color: #6A737D">// Define different processing behaviors using lambda expressions</span></span>
<span class="line"><span style="color: #E1E4E8">        NumberProcessor squareProcessor </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> (num) </span><span style="color: #F97583">-&gt;</span><span style="color: #E1E4E8"> {</span></span>
<span class="line"><span style="color: #E1E4E8">            </span><span style="color: #F97583">int</span><span style="color: #E1E4E8"> result </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> num </span><span style="color: #F97583">*</span><span style="color: #E1E4E8"> num;</span></span>
<span class="line"><span style="color: #E1E4E8">            System.out.</span><span style="color: #B392F0">println</span><span style="color: #E1E4E8">(</span><span style="color: #9ECBFF">&quot;Square of &quot;</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">+</span><span style="color: #E1E4E8"> num </span><span style="color: #F97583">+</span><span style="color: #E1E4E8"> </span><span style="color: #9ECBFF">&quot;: &quot;</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">+</span><span style="color: #E1E4E8"> result);</span></span>
<span class="line"><span style="color: #E1E4E8">        };</span></span>
<span class="line"></span>
<span class="line"><span style="color: #E1E4E8">        NumberProcessor cubeProcessor </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> (num) </span><span style="color: #F97583">-&gt;</span><span style="color: #E1E4E8"> {</span></span>
<span class="line"><span style="color: #E1E4E8">            </span><span style="color: #F97583">int</span><span style="color: #E1E4E8"> result </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> num </span><span style="color: #F97583">*</span><span style="color: #E1E4E8"> num </span><span style="color: #F97583">*</span><span style="color: #E1E4E8"> num;</span></span>
<span class="line"><span style="color: #E1E4E8">            System.out.</span><span style="color: #B392F0">println</span><span style="color: #E1E4E8">(</span><span style="color: #9ECBFF">&quot;Cube of &quot;</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">+</span><span style="color: #E1E4E8"> num </span><span style="color: #F97583">+</span><span style="color: #E1E4E8"> </span><span style="color: #9ECBFF">&quot;: &quot;</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">+</span><span style="color: #E1E4E8"> result);</span></span>
<span class="line"><span style="color: #E1E4E8">        };</span></span>
<span class="line"></span>
<span class="line"><span style="color: #E1E4E8">        </span><span style="color: #6A737D">// Process the numbers with different behaviors</span></span>
<span class="line"><span style="color: #E1E4E8">        System.out.</span><span style="color: #B392F0">println</span><span style="color: #E1E4E8">(</span><span style="color: #9ECBFF">&quot;Processing with squareProcessor:&quot;</span><span style="color: #E1E4E8">);</span></span>
<span class="line"><span style="color: #E1E4E8">        </span><span style="color: #B392F0">processNumbers</span><span style="color: #E1E4E8">(numbers, squareProcessor);</span></span>
<span class="line"></span>
<span class="line"><span style="color: #E1E4E8">        System.out.</span><span style="color: #B392F0">println</span><span style="color: #E1E4E8">(</span><span style="color: #9ECBFF">&quot;Processing with cubeProcessor:&quot;</span><span style="color: #E1E4E8">);</span></span>
<span class="line"><span style="color: #E1E4E8">        </span><span style="color: #B392F0">processNumbers</span><span style="color: #E1E4E8">(numbers, cubeProcessor);</span></span>
<span class="line"><span style="color: #E1E4E8">    }</span></span>
<span class="line"><span style="color: #E1E4E8">}</span></span></code></pre></div>



<p>The provided code example demonstrates how lambda expressions can be effectively utilized in Java to provide different processing behaviors for a list of integers. The code is broken down into various parts, each serving a specific purpose.</p>



<h3 class="wp-block-heading">Interface Definition: NumberProcessor</h3>



<div class="wp-block-kevinbatdorf-code-block-pro" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:clamp(14px, .875rem, 21px);font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:clamp(20px, 1.25rem, 30px);--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:10px 0px 10px 16px;margin-bottom:-2px;width:100%;text-align:left;background-color:#2f363c;color:#d3d7dd">Java</span><span role="button" tabindex="0" data-code="interface NumberProcessor {
    void process(int number);
}" style="color:#e1e4e8;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki github-dark" style="background-color: #24292e" tabindex="0"><code><span class="line"><span style="color: #F97583">interface</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">NumberProcessor</span><span style="color: #E1E4E8"> {</span></span>
<span class="line"><span style="color: #E1E4E8">    </span><span style="color: #F97583">void</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">process</span><span style="color: #E1E4E8">(</span><span style="color: #F97583">int</span><span style="color: #E1E4E8"> </span><span style="color: #FFAB70">number</span><span style="color: #E1E4E8">);</span></span>
<span class="line"><span style="color: #E1E4E8">}</span></span></code></pre></div>



<p>This section defines an interface named <code>NumberProcessor</code>. It has a single abstract method <code>process</code> that takes an integer as its argument. The method does not return anything (<code>void</code>). Any concrete implementation of this interface will have to define what to do with the given integer.</p>



<h3 class="wp-block-heading">Utility Method: processNumbers</h3>



<div class="wp-block-kevinbatdorf-code-block-pro" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:clamp(14px, .875rem, 21px);font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:clamp(20px, 1.25rem, 30px);--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:10px 0px 10px 16px;margin-bottom:-2px;width:100%;text-align:left;background-color:#2f363c;color:#d3d7dd">Java</span><span role="button" tabindex="0" data-code="static void processNumbers(List&lt;Integer&gt; numbers, NumberProcessor processor) {
    for (int num : numbers) {
        processor.process(num);
    }
}" style="color:#e1e4e8;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki github-dark" style="background-color: #24292e" tabindex="0"><code><span class="line"><span style="color: #F97583">static</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">void</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">processNumbers</span><span style="color: #E1E4E8">(List</span><span style="color: #F97583">&lt;</span><span style="color: #E1E4E8">Integer</span><span style="color: #F97583">&gt;</span><span style="color: #E1E4E8"> numbers, NumberProcessor processor) {</span></span>
<span class="line"><span style="color: #E1E4E8">    </span><span style="color: #F97583">for</span><span style="color: #E1E4E8"> (</span><span style="color: #F97583">int</span><span style="color: #E1E4E8"> num </span><span style="color: #F97583">:</span><span style="color: #E1E4E8"> numbers) {</span></span>
<span class="line"><span style="color: #E1E4E8">        processor.</span><span style="color: #B392F0">process</span><span style="color: #E1E4E8">(num);</span></span>
<span class="line"><span style="color: #E1E4E8">    }</span></span>
<span class="line"><span style="color: #E1E4E8">}</span></span></code></pre></div>



<p>Here, a utility method named <code>processNumbers</code> is declared as static. It takes a list of integers (<code>List&lt;Integer&gt; numbers</code>) and an object that implements <code>NumberProcessor</code> as its parameters. This method iterates over the list of numbers and applies the <code>process</code> method defined in the <code>NumberProcessor</code> interface. The actual behavior depends on the implementation of <code>NumberProcessor</code> passed to it.</p>



<h3 class="wp-block-heading">Main Method and Lambda Expressions</h3>



<div class="wp-block-kevinbatdorf-code-block-pro" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:clamp(14px, .875rem, 21px);font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:clamp(20px, 1.25rem, 30px);--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:10px 0px 10px 16px;margin-bottom:-2px;width:100%;text-align:left;background-color:#2f363c;color:#d3d7dd">Java</span><span role="button" tabindex="0" data-code="public static void main(String[] args) {
    List&lt;Integer&gt; numbers = Arrays.asList(1, 2, 3, 4, 5);
    
    // Lambda expressions for different behaviors
    NumberProcessor squareProcessor = (num) -&gt; {
        int result = num * num;
        System.out.println(&quot;Square of &quot; + num + &quot;: &quot; + result);
    };

    NumberProcessor cubeProcessor = (num) -&gt; {
        int result = num * num * num;
        System.out.println(&quot;Cube of &quot; + num + &quot;: &quot; + result);
    };
    
    // Using the defined behaviors
    System.out.println(&quot;Processing with squareProcessor:&quot;);
    processNumbers(numbers, squareProcessor);

    System.out.println(&quot;Processing with cubeProcessor:&quot;);
    processNumbers(numbers, cubeProcessor);
}" style="color:#e1e4e8;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki github-dark" style="background-color: #24292e" tabindex="0"><code><span class="line"><span style="color: #F97583">public</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">static</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">void</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">main</span><span style="color: #E1E4E8">(</span><span style="color: #F97583">String</span><span style="color: #E1E4E8">[] args) {</span></span>
<span class="line"><span style="color: #E1E4E8">    List&lt;</span><span style="color: #F97583">Integer</span><span style="color: #E1E4E8">&gt; numbers </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> Arrays.</span><span style="color: #B392F0">asList</span><span style="color: #E1E4E8">(</span><span style="color: #79B8FF">1</span><span style="color: #E1E4E8">, </span><span style="color: #79B8FF">2</span><span style="color: #E1E4E8">, </span><span style="color: #79B8FF">3</span><span style="color: #E1E4E8">, </span><span style="color: #79B8FF">4</span><span style="color: #E1E4E8">, </span><span style="color: #79B8FF">5</span><span style="color: #E1E4E8">);</span></span>
<span class="line"><span style="color: #E1E4E8">    </span></span>
<span class="line"><span style="color: #E1E4E8">    </span><span style="color: #6A737D">// Lambda expressions for different behaviors</span></span>
<span class="line"><span style="color: #E1E4E8">    NumberProcessor squareProcessor </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> (num) </span><span style="color: #F97583">-&gt;</span><span style="color: #E1E4E8"> {</span></span>
<span class="line"><span style="color: #E1E4E8">        </span><span style="color: #F97583">int</span><span style="color: #E1E4E8"> result </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> num </span><span style="color: #F97583">*</span><span style="color: #E1E4E8"> num;</span></span>
<span class="line"><span style="color: #E1E4E8">        System.out.</span><span style="color: #B392F0">println</span><span style="color: #E1E4E8">(</span><span style="color: #9ECBFF">&quot;Square of &quot;</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">+</span><span style="color: #E1E4E8"> num </span><span style="color: #F97583">+</span><span style="color: #E1E4E8"> </span><span style="color: #9ECBFF">&quot;: &quot;</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">+</span><span style="color: #E1E4E8"> result);</span></span>
<span class="line"><span style="color: #E1E4E8">    };</span></span>
<span class="line"></span>
<span class="line"><span style="color: #E1E4E8">    NumberProcessor cubeProcessor </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> (num) </span><span style="color: #F97583">-&gt;</span><span style="color: #E1E4E8"> {</span></span>
<span class="line"><span style="color: #E1E4E8">        </span><span style="color: #F97583">int</span><span style="color: #E1E4E8"> result </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> num </span><span style="color: #F97583">*</span><span style="color: #E1E4E8"> num </span><span style="color: #F97583">*</span><span style="color: #E1E4E8"> num;</span></span>
<span class="line"><span style="color: #E1E4E8">        System.out.</span><span style="color: #B392F0">println</span><span style="color: #E1E4E8">(</span><span style="color: #9ECBFF">&quot;Cube of &quot;</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">+</span><span style="color: #E1E4E8"> num </span><span style="color: #F97583">+</span><span style="color: #E1E4E8"> </span><span style="color: #9ECBFF">&quot;: &quot;</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">+</span><span style="color: #E1E4E8"> result);</span></span>
<span class="line"><span style="color: #E1E4E8">    };</span></span>
<span class="line"><span style="color: #E1E4E8">    </span></span>
<span class="line"><span style="color: #E1E4E8">    </span><span style="color: #6A737D">// Using the defined behaviors</span></span>
<span class="line"><span style="color: #E1E4E8">    System.out.</span><span style="color: #B392F0">println</span><span style="color: #E1E4E8">(</span><span style="color: #9ECBFF">&quot;Processing with squareProcessor:&quot;</span><span style="color: #E1E4E8">);</span></span>
<span class="line"><span style="color: #E1E4E8">    </span><span style="color: #B392F0">processNumbers</span><span style="color: #E1E4E8">(numbers, squareProcessor);</span></span>
<span class="line"></span>
<span class="line"><span style="color: #E1E4E8">    System.out.</span><span style="color: #B392F0">println</span><span style="color: #E1E4E8">(</span><span style="color: #9ECBFF">&quot;Processing with cubeProcessor:&quot;</span><span style="color: #E1E4E8">);</span></span>
<span class="line"><span style="color: #E1E4E8">    </span><span style="color: #B392F0">processNumbers</span><span style="color: #E1E4E8">(numbers, cubeProcessor);</span></span>
<span class="line"><span style="color: #E1E4E8">}</span></span></code></pre></div>



<p>In the <code>main</code> method:</p>



<ol class="wp-block-list">
<li>A list of integers is created using <code>Arrays.asList()</code>.</li>



<li>Two lambda expressions are defined, each providing different implementations for the <code>NumberProcessor</code> interface.
<ul class="wp-block-list">
<li><code>squareProcessor</code>: Takes an integer <code>num</code> and prints its square.</li>



<li><code>cubeProcessor</code>: Takes an integer <code>num</code> and prints its cube.</li>
</ul>
</li>



<li>The <code>processNumbers</code> method is then called twice, each time with a different implementation of <code>NumberProcessor</code> (either <code>squareProcessor</code> or <code>cubeProcessor</code>).</li>
</ol>



<p>This code example demonstrates the flexibility and conciseness that lambda expressions bring to Java. By defining different lambda expressions, you can easily modify the behavior of how the numbers are processed without changing the core logic encapsulated in the <code>processNumbers</code> method.</p>



<h2 class="wp-block-heading">Unveiling the Power of Lambdas</h2>



<p>Lambda expressions enable elegant solutions for various scenarios. They are extensively used in Java’s Stream API, allowing for streamlined data manipulation and transformation (aggregate operations). Additionally, lambda expressions play a crucial role in implementing the <a href="https://www.digitalocean.com/community/tutorials/observer-design-pattern-in-java" target="_blank" rel="noreferrer noopener">Observer design pattern</a> and are vital in event-driven programming.</p>



<p>As you explore the realm of lambda expressions, consider diving deeper into topics like method references, effectively final variables, and their impact on performance and memory utilization.</p>



<h2 class="wp-block-heading">Exploring Further Possibilities</h2>



<p>Lambda expressions are just the tip of the iceberg in the world of functional programming. As you delve deeper into this paradigm, you’ll uncover advanced concepts and techniques. Explore topics like partial application, currying, and monads to broaden your functional programming toolkit.</p>



<p>Incorporate lambda expressions into your Java code to create more maintainable, expressive, and efficient solutions. Embrace the power of functional programming, and you’ll find yourself tackling complex problems with elegance and ease.</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<p>In this article, we&#8217;ve delved into the intricate world of lambda expressions in Java. We&#8217;ve explored their definition, the essential link with functional interfaces, key functional interfaces provided by Java, practical examples, and fascinating applications. By mastering lambda expressions, you&#8217;ve equipped yourself with a powerful tool to write more concise, readable, and functional code.</p>



<p>As you continue your journey in Java software development, remember that lambda expressions are a valuable addition to your toolkit. Embrace their elegance and expressive nature, and leverage them in scenarios where functional programming principles shine the brightest. As you venture into advanced topics and expand your horizons, you&#8217;ll find lambda expressions to be an invaluable asset in your pursuit of writing exceptional Java code. Happy coding!</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>A Beginner’s Guide to Java (Jakarta) Persistence API (JPA)</title>
		<link>https://blog.j-dev.app/a-beginners-guide-to-java-persistence-api-jpa/</link>
		
		<dc:creator><![CDATA[JuanC]]></dc:creator>
		<pubDate>Sat, 12 Aug 2023 06:39:29 +0000</pubDate>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[JPA]]></category>
		<guid isPermaLink="false">https://blog.j-dev.app/?page_id=73</guid>

					<description><![CDATA[As Java developers embark on their journey to build robust and scalable applications, one critical aspect they encounter is database interaction. Traditionally, this process involved writing tedious SQL queries, mapping result sets to Java objects, and handling database transactions manually. However, Java Persistence API (JPA) revolutionized this paradigm, offering a high-level, object-relational mapping (ORM) framework [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p>As Java developers embark on their journey to build robust and scalable applications, one critical aspect they encounter is database interaction. Traditionally, this process involved writing tedious SQL queries, mapping result sets to Java objects, and handling database transactions manually. However, Java Persistence API (JPA) revolutionized this paradigm, offering a high-level, object-relational mapping (ORM) framework that simplifies database interaction in Java.</p>



<p>In this beginner’s guide, we will explore the fundamentals of JPA, its key concepts, and how it streamlines database interactions. We will cover essential topics, including entity classes, annotations, EntityManager, querying data, and transactions, while providing code samples to illustrate each concept. By the end of this article, you will have a solid understanding of JPA and be ready to incorporate its power into your Java applications.</p>



<h2 class="wp-block-heading">I. Understanding JPA Fundamentals</h2>



<h3 class="wp-block-heading">A. What is JPA?</h3>



<p>Java Persistence API (now Jakarta Persistence API or simply JPA) is a specification in Java EE (Java Platform, Enterprise Edition) that defines a standard approach to object-relational mapping (ORM). It bridges the gap between object-oriented programming and relational databases, allowing developers to work with Java objects while seamlessly persisting data in a relational database.</p>



<p>JPA provides a set of annotations and classes that enable developers to map Java objects to database tables, manage their persistence, and perform database operations using object-oriented syntax. The goal is to minimize boilerplate code and simplify the development of database-driven applications.</p>



<h3 class="wp-block-heading">B. Key Concepts in JPA</h3>



<h4 class="wp-block-heading">1. Entity Classes</h4>



<p>In JPA, entity classes are regular Java classes representing objects that need to be persisted in the database. Each entity class corresponds to a database table, and its attributes represent the table’s columns. Developers annotate these classes with JPA annotations to specify how the objects are mapped to the database.</p>



<h4 class="wp-block-heading">2. EntityManager</h4>



<p>The EntityManager is the central interface for managing entity objects in JPA. It serves as a bridge between the application code and the underlying database. The EntityManager is responsible for creating, persisting, updating, and deleting entities, as well as for querying the database.</p>



<h4 class="wp-block-heading">3. Annotations</h4>



<p>JPA leverages annotations to define mappings between entity classes and database tables, as well as to provide additional metadata for the EntityManager. Annotations like <code>@Entity</code>, <code>@Id</code>, <code>@Column</code>, and <code>@OneToMany</code> play a crucial role in defining the structure and relationships of entity classes.</p>



<h2 class="wp-block-heading">II. Creating Entity Classes and Mapping Annotations</h2>



<p>Let’s dive into the practical side of JPA by creating entity classes and understanding how to map them to database tables using annotations.</p>



<h3 class="wp-block-heading">A. Setting Up the Environment</h3>



<p>Before getting started with JPA, ensure you have the necessary dependencies and configurations in your Java project. JPA relies on Java EE or Java SE, so make sure you have a compatible application server or Java Persistence provider, such as <a rel="noreferrer noopener" href="https://hibernate.org/" target="_blank">Hibernate</a> or <a rel="noreferrer noopener" href="https://projects.eclipse.org/projects/ee4j.eclipselink" target="_blank">EclipseLink</a>.</p>



<h3 class="wp-block-heading">B. Creating the Entity Class</h3>



<p>Suppose we want to create an entity class to represent a “Product” in an e-commerce application. The entity class will have attributes like “id,” “name,” “price,” and “category.”</p>



<div class="wp-block-kevinbatdorf-code-block-pro" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:clamp(14px, .875rem, 21px);font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:clamp(20px, 1.25rem, 30px);--cbp-tab-width:4;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:10px 0px 10px 16px;margin-bottom:-2px;width:100%;text-align:left;background-color:#2f363c;color:#d3d7dd">Java</span><span role="button" tabindex="0" data-code="import jakarta.persistence.*;

@Entity
public class Product {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    
    @Column(nullable = false)
    private String name;
    
    @Column(nullable = false)
    private double price;
    
    private String category;

    // Getters and setters (omitted for brevity)

}" style="color:#e1e4e8;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki github-dark" style="background-color: #24292e" tabindex="0"><code><span class="line"><span style="color: #F97583">import</span><span style="color: #E1E4E8"> jakarta.persistence.</span><span style="color: #79B8FF">*</span><span style="color: #E1E4E8">;</span></span>
<span class="line"></span>
<span class="line"><span style="color: #E1E4E8">@</span><span style="color: #F97583">Entity</span></span>
<span class="line"><span style="color: #F97583">public</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">class</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">Product</span><span style="color: #E1E4E8"> {</span></span>
<span class="line"></span>
<span class="line"><span style="color: #E1E4E8">    @</span><span style="color: #F97583">Id</span></span>
<span class="line"><span style="color: #E1E4E8">    @</span><span style="color: #F97583">GeneratedValue</span><span style="color: #E1E4E8">(</span><span style="color: #79B8FF">strategy</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> GenerationType.IDENTITY)</span></span>
<span class="line"><span style="color: #E1E4E8">    </span><span style="color: #F97583">private</span><span style="color: #E1E4E8"> Long id;</span></span>
<span class="line"><span style="color: #E1E4E8">    </span></span>
<span class="line"><span style="color: #E1E4E8">    @</span><span style="color: #F97583">Column</span><span style="color: #E1E4E8">(</span><span style="color: #79B8FF">nullable</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> </span><span style="color: #79B8FF">false</span><span style="color: #E1E4E8">)</span></span>
<span class="line"><span style="color: #E1E4E8">    </span><span style="color: #F97583">private</span><span style="color: #E1E4E8"> String name;</span></span>
<span class="line"><span style="color: #E1E4E8">    </span></span>
<span class="line"><span style="color: #E1E4E8">    @</span><span style="color: #F97583">Column</span><span style="color: #E1E4E8">(</span><span style="color: #79B8FF">nullable</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> </span><span style="color: #79B8FF">false</span><span style="color: #E1E4E8">)</span></span>
<span class="line"><span style="color: #E1E4E8">    </span><span style="color: #F97583">private</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">double</span><span style="color: #E1E4E8"> price;</span></span>
<span class="line"><span style="color: #E1E4E8">    </span></span>
<span class="line"><span style="color: #E1E4E8">    </span><span style="color: #F97583">private</span><span style="color: #E1E4E8"> String category;</span></span>
<span class="line"></span>
<span class="line"><span style="color: #E1E4E8">    </span><span style="color: #6A737D">// Getters and setters (omitted for brevity)</span></span>
<span class="line"></span>
<span class="line"><span style="color: #E1E4E8">}</span></span></code></pre></div>



<p>In the above code, we annotated the class with <code>@Entity</code>, indicating that it is an entity that needs to be persisted in the database. The <code>@Id</code> annotation specifies the primary key of the entity, and <code>@GeneratedValue</code> with strategy <code>GenerationType.IDENTITY</code> indicates that the primary key will be automatically generated.</p>



<p>The <code>@Column</code> annotations on the attributes define the mapping of the attributes to the corresponding columns in the database. The <code>nullable = false</code> attribute ensures that the “name” and “price” attributes cannot be null in the database.</p>



<h3 class="wp-block-heading">C. Establishing Persistence Context</h3>



<p>The next step is to set up the persistence context and obtain an instance of EntityManager to interact with the database. The persistence context is a set of managed entity instances, and EntityManager is the entry point to this context.</p>



<div class="wp-block-kevinbatdorf-code-block-pro" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:clamp(14px, .875rem, 21px);font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:clamp(20px, 1.25rem, 30px);--cbp-tab-width:4;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:10px 0px 10px 16px;margin-bottom:-2px;width:100%;text-align:left;background-color:#2f363c;color:#d3d7dd">Java</span><span role="button" tabindex="0" data-code="import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.Persistence;

public class Main {

    public static void main(String[] args) {
        EntityManagerFactory emf = Persistence.createEntityManagerFactory(&quot;my-persistence-unit&quot;);
        EntityManager em = emf.createEntityManager();
        // Perform database operations using EntityManager
        em.close();
        emf.close();
    }

}" style="color:#e1e4e8;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki github-dark" style="background-color: #24292e" tabindex="0"><code><span class="line"><span style="color: #F97583">import</span><span style="color: #E1E4E8"> jakarta.persistence.EntityManager;</span></span>
<span class="line"><span style="color: #F97583">import</span><span style="color: #E1E4E8"> jakarta.persistence.EntityManagerFactory;</span></span>
<span class="line"><span style="color: #F97583">import</span><span style="color: #E1E4E8"> jakarta.persistence.Persistence;</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F97583">public</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">class</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">Main</span><span style="color: #E1E4E8"> {</span></span>
<span class="line"></span>
<span class="line"><span style="color: #E1E4E8">    </span><span style="color: #F97583">public</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">static</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">void</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">main</span><span style="color: #E1E4E8">(</span><span style="color: #F97583">String</span><span style="color: #E1E4E8">[] </span><span style="color: #FFAB70">args</span><span style="color: #E1E4E8">) {</span></span>
<span class="line"><span style="color: #E1E4E8">        EntityManagerFactory emf </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> Persistence.</span><span style="color: #B392F0">createEntityManagerFactory</span><span style="color: #E1E4E8">(</span><span style="color: #9ECBFF">&quot;my-persistence-unit&quot;</span><span style="color: #E1E4E8">);</span></span>
<span class="line"><span style="color: #E1E4E8">        EntityManager em </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> emf.</span><span style="color: #B392F0">createEntityManager</span><span style="color: #E1E4E8">();</span></span>
<span class="line"><span style="color: #E1E4E8">        </span><span style="color: #6A737D">// Perform database operations using EntityManager</span></span>
<span class="line"><span style="color: #E1E4E8">        em.</span><span style="color: #B392F0">close</span><span style="color: #E1E4E8">();</span></span>
<span class="line"><span style="color: #E1E4E8">        emf.</span><span style="color: #B392F0">close</span><span style="color: #E1E4E8">();</span></span>
<span class="line"><span style="color: #E1E4E8">    }</span></span>
<span class="line"></span>
<span class="line"><span style="color: #E1E4E8">}</span></span></code></pre></div>



<p>In this code, we create an EntityManagerFactory using <code>Persistence.createEntityManagerFactory("my-persistence-unit")</code>, where “my-persistence-unit” corresponds to the persistence unit defined in the “persistence.xml” file. We then create an EntityManager using <code>emf.createEntityManager()</code>.</p>



<h3 class="wp-block-heading">D. Configuring Persistence Unit</h3>



<p>The “persistence.xml” file is essential for configuring the persistence unit, which defines the properties for connecting to the database and managing entity classes. Place this file in the “META-INF” directory of your classpath. If you are using JPA 2 or older, you should change &#8220;jakarta&#8221; by &#8220;javax&#8221; in the contents of <code>persistence.xml</code>.</p>



<div class="wp-block-kevinbatdorf-code-block-pro" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:clamp(14px, .875rem, 21px);font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:clamp(20px, 1.25rem, 30px);--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:10px 0px 10px 16px;margin-bottom:-2px;width:100%;text-align:left;background-color:#2f363c;color:#d3d7dd">XML</span><span role="button" tabindex="0" data-code="&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;persistence version=&quot;2.2&quot; xmlns=&quot;http://xmlns.jcp.org/xml/ns/persistence&quot;&gt;
  &lt;persistence-unit name=&quot;persistence_unit&quot; transaction-type=&quot;RESOURCE_LOCAL&quot;&gt;
    &lt;provider&gt;org.eclipse.persistence.jpa.PersistenceProvider&lt;/provider&gt;
    &lt;exclude-unlisted-classes&gt;false&lt;/exclude-unlisted-classes&gt;
    &lt;properties&gt;
      &lt;property name=&quot;jakarta.persistence.jdbc.url&quot; value=&quot;jdbc:mysql://localhost:3306/database&quot;/&gt;
      &lt;property name=&quot;jakarta.persistence.jdbc.user&quot; value=&quot;user&quot;/&gt;
      &lt;property name=&quot;jakarta.persistence.jdbc.password&quot; value=&quot;password&quot;/&gt;
      &lt;property name=&quot;jakarta.persistence.jdbc.driver&quot; value=&quot;com.mysql.cj.jdbc.Driver&quot;/&gt;
      &lt;property name=&quot;jakarta.persistence.schema-generation.database.action&quot; value=&quot;create&quot;/&gt;
    &lt;/properties&gt;
  &lt;/persistence-unit&gt;
&lt;/persistence&gt;" style="color:#e1e4e8;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki github-dark" style="background-color: #24292e" tabindex="0"><code><span class="line"><span style="color: #E1E4E8">&lt;?</span><span style="color: #85E89D">xml</span><span style="color: #B392F0"> version</span><span style="color: #E1E4E8">=</span><span style="color: #9ECBFF">&quot;1.0&quot;</span><span style="color: #B392F0"> encoding</span><span style="color: #E1E4E8">=</span><span style="color: #9ECBFF">&quot;UTF-8&quot;</span><span style="color: #E1E4E8">?&gt;</span></span>
<span class="line"><span style="color: #E1E4E8">&lt;</span><span style="color: #85E89D">persistence</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">version</span><span style="color: #E1E4E8">=</span><span style="color: #9ECBFF">&quot;2.2&quot;</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">xmlns</span><span style="color: #E1E4E8">=</span><span style="color: #9ECBFF">&quot;http://xmlns.jcp.org/xml/ns/persistence&quot;</span><span style="color: #E1E4E8">&gt;</span></span>
<span class="line"><span style="color: #E1E4E8">  &lt;</span><span style="color: #85E89D">persistence-unit</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">name</span><span style="color: #E1E4E8">=</span><span style="color: #9ECBFF">&quot;persistence_unit&quot;</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">transaction-type</span><span style="color: #E1E4E8">=</span><span style="color: #9ECBFF">&quot;RESOURCE_LOCAL&quot;</span><span style="color: #E1E4E8">&gt;</span></span>
<span class="line"><span style="color: #E1E4E8">    &lt;</span><span style="color: #85E89D">provider</span><span style="color: #E1E4E8">&gt;org.eclipse.persistence.jpa.PersistenceProvider&lt;/</span><span style="color: #85E89D">provider</span><span style="color: #E1E4E8">&gt;</span></span>
<span class="line"><span style="color: #E1E4E8">    &lt;</span><span style="color: #85E89D">exclude-unlisted-classes</span><span style="color: #E1E4E8">&gt;false&lt;/</span><span style="color: #85E89D">exclude-unlisted-classes</span><span style="color: #E1E4E8">&gt;</span></span>
<span class="line"><span style="color: #E1E4E8">    &lt;</span><span style="color: #85E89D">properties</span><span style="color: #E1E4E8">&gt;</span></span>
<span class="line"><span style="color: #E1E4E8">      &lt;</span><span style="color: #85E89D">property</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">name</span><span style="color: #E1E4E8">=</span><span style="color: #9ECBFF">&quot;jakarta.persistence.jdbc.url&quot;</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">value</span><span style="color: #E1E4E8">=</span><span style="color: #9ECBFF">&quot;jdbc:mysql://localhost:3306/database&quot;</span><span style="color: #E1E4E8">/&gt;</span></span>
<span class="line"><span style="color: #E1E4E8">      &lt;</span><span style="color: #85E89D">property</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">name</span><span style="color: #E1E4E8">=</span><span style="color: #9ECBFF">&quot;jakarta.persistence.jdbc.user&quot;</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">value</span><span style="color: #E1E4E8">=</span><span style="color: #9ECBFF">&quot;user&quot;</span><span style="color: #E1E4E8">/&gt;</span></span>
<span class="line"><span style="color: #E1E4E8">      &lt;</span><span style="color: #85E89D">property</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">name</span><span style="color: #E1E4E8">=</span><span style="color: #9ECBFF">&quot;jakarta.persistence.jdbc.password&quot;</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">value</span><span style="color: #E1E4E8">=</span><span style="color: #9ECBFF">&quot;password&quot;</span><span style="color: #E1E4E8">/&gt;</span></span>
<span class="line"><span style="color: #E1E4E8">      &lt;</span><span style="color: #85E89D">property</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">name</span><span style="color: #E1E4E8">=</span><span style="color: #9ECBFF">&quot;jakarta.persistence.jdbc.driver&quot;</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">value</span><span style="color: #E1E4E8">=</span><span style="color: #9ECBFF">&quot;com.mysql.cj.jdbc.Driver&quot;</span><span style="color: #E1E4E8">/&gt;</span></span>
<span class="line"><span style="color: #E1E4E8">      &lt;</span><span style="color: #85E89D">property</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">name</span><span style="color: #E1E4E8">=</span><span style="color: #9ECBFF">&quot;jakarta.persistence.schema-generation.database.action&quot;</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">value</span><span style="color: #E1E4E8">=</span><span style="color: #9ECBFF">&quot;create&quot;</span><span style="color: #E1E4E8">/&gt;</span></span>
<span class="line"><span style="color: #E1E4E8">    &lt;/</span><span style="color: #85E89D">properties</span><span style="color: #E1E4E8">&gt;</span></span>
<span class="line"><span style="color: #E1E4E8">  &lt;/</span><span style="color: #85E89D">persistence-unit</span><span style="color: #E1E4E8">&gt;</span></span>
<span class="line"><span style="color: #E1E4E8">&lt;/</span><span style="color: #85E89D">persistence</span><span style="color: #E1E4E8">&gt;</span></span></code></pre></div>



<p>In this configuration, we specify the provider as a <code>org.eclipse.persistence.jpa.PersistenceProvider</code> or <a href="https://eclipse.dev/eclipselink/" target="_blank" rel="noreferrer noopener">EclipseLink</a>, and with <code>&lt;exclude-unlisted-classes&gt;false&lt;/exclude-unlisted-classes&gt;</code> we are telling EclipseLink to automatically search every class annotated with <code>@Entity</code> to be added to the database. Additionally, we define the database connection properties, such as URL, username, password, and driver class name.</p>



<h2 class="wp-block-heading">III. Persisting and Querying Data using JPA</h2>



<p>With the entity class and EntityManager set up, we can now proceed to persist data in the database and query existing data.</p>



<h3 class="wp-block-heading">A. Persisting Data</h3>



<p>To save a new product to the database, we use the EntityManager’s persist() method:</p>



<div class="wp-block-kevinbatdorf-code-block-pro" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:clamp(14px, .875rem, 21px);font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:clamp(20px, 1.25rem, 30px);--cbp-tab-width:4;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:10px 0px 10px 16px;margin-bottom:-2px;width:100%;text-align:left;background-color:#2f363c;color:#d3d7dd">Java</span><span role="button" tabindex="0" data-code="public class Main {

    public static void main(String[] args) {
        EntityManagerFactory emf = Persistence.createEntityManagerFactory(&quot;my-persistence-unit&quot;);
        EntityManager em = emf.createEntityManager();

        // Creating a new product
        Product newProduct = new Product();
        newProduct.setName(&quot;Laptop&quot;);
        newProduct.setPrice(1000.0);
        newProduct.setCategory(&quot;Electronics&quot;);

        // Persisting the product to the database
        em.getTransaction().begin();
        em.persist(newProduct);
        em.getTransaction().commit();

        em.close();
        emf.close();
    }

}" style="color:#e1e4e8;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki github-dark" style="background-color: #24292e" tabindex="0"><code><span class="line"><span style="color: #F97583">public</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">class</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">Main</span><span style="color: #E1E4E8"> {</span></span>
<span class="line"></span>
<span class="line"><span style="color: #E1E4E8">    </span><span style="color: #F97583">public</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">static</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">void</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">main</span><span style="color: #E1E4E8">(</span><span style="color: #F97583">String</span><span style="color: #E1E4E8">[] </span><span style="color: #FFAB70">args</span><span style="color: #E1E4E8">) {</span></span>
<span class="line"><span style="color: #E1E4E8">        EntityManagerFactory emf </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> Persistence.</span><span style="color: #B392F0">createEntityManagerFactory</span><span style="color: #E1E4E8">(</span><span style="color: #9ECBFF">&quot;my-persistence-unit&quot;</span><span style="color: #E1E4E8">);</span></span>
<span class="line"><span style="color: #E1E4E8">        EntityManager em </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> emf.</span><span style="color: #B392F0">createEntityManager</span><span style="color: #E1E4E8">();</span></span>
<span class="line"></span>
<span class="line"><span style="color: #E1E4E8">        </span><span style="color: #6A737D">// Creating a new product</span></span>
<span class="line"><span style="color: #E1E4E8">        Product newProduct </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">new</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">Product</span><span style="color: #E1E4E8">();</span></span>
<span class="line"><span style="color: #E1E4E8">        newProduct.</span><span style="color: #B392F0">setName</span><span style="color: #E1E4E8">(</span><span style="color: #9ECBFF">&quot;Laptop&quot;</span><span style="color: #E1E4E8">);</span></span>
<span class="line"><span style="color: #E1E4E8">        newProduct.</span><span style="color: #B392F0">setPrice</span><span style="color: #E1E4E8">(</span><span style="color: #79B8FF">1000.0</span><span style="color: #E1E4E8">);</span></span>
<span class="line"><span style="color: #E1E4E8">        newProduct.</span><span style="color: #B392F0">setCategory</span><span style="color: #E1E4E8">(</span><span style="color: #9ECBFF">&quot;Electronics&quot;</span><span style="color: #E1E4E8">);</span></span>
<span class="line"></span>
<span class="line"><span style="color: #E1E4E8">        </span><span style="color: #6A737D">// Persisting the product to the database</span></span>
<span class="line"><span style="color: #E1E4E8">        em.</span><span style="color: #B392F0">getTransaction</span><span style="color: #E1E4E8">().</span><span style="color: #B392F0">begin</span><span style="color: #E1E4E8">();</span></span>
<span class="line"><span style="color: #E1E4E8">        em.</span><span style="color: #B392F0">persist</span><span style="color: #E1E4E8">(newProduct);</span></span>
<span class="line"><span style="color: #E1E4E8">        em.</span><span style="color: #B392F0">getTransaction</span><span style="color: #E1E4E8">().</span><span style="color: #B392F0">commit</span><span style="color: #E1E4E8">();</span></span>
<span class="line"></span>
<span class="line"><span style="color: #E1E4E8">        em.</span><span style="color: #B392F0">close</span><span style="color: #E1E4E8">();</span></span>
<span class="line"><span style="color: #E1E4E8">        emf.</span><span style="color: #B392F0">close</span><span style="color: #E1E4E8">();</span></span>
<span class="line"><span style="color: #E1E4E8">    }</span></span>
<span class="line"></span>
<span class="line"><span style="color: #E1E4E8">}</span></span></code></pre></div>



<p>In this code, we create a new instance of Product and set its attributes. We then begin a transaction with <code>em.getTransaction().begin()</code>, persist the product using <code>em.persist(newProduct)</code>, and commit the transaction with <code>em.getTransaction().commit()</code>.</p>



<h3 class="wp-block-heading">B. Querying Data</h3>



<p>JPA allows us to query data from the database using JPQL (Java Persistence Query Language), which is similar to SQL but operates on entity objects.</p>



<div class="wp-block-kevinbatdorf-code-block-pro" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:clamp(14px, .875rem, 21px);font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:clamp(20px, 1.25rem, 30px);--cbp-tab-width:4;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:10px 0px 10px 16px;margin-bottom:-2px;width:100%;text-align:left;background-color:#2f363c;color:#d3d7dd">Java</span><span role="button" tabindex="0" data-code="import jakarta.persistence.TypedQuery;
import java.util.List;

public class Main {

    public static void main(String[] args) {
        EntityManagerFactory emf = Persistence.createEntityManagerFactory(&quot;my-persistence-unit&quot;);
        EntityManager em = emf.createEntityManager();

        // Querying products by category
        String jpql = &quot;SELECT p FROM Product p WHERE p.category = :category&quot;;
        TypedQuery&lt;Product&gt; query = em.createQuery(jpql, Product.class);
        query.setParameter(&quot;category&quot;, &quot;Electronics&quot;);

        List&lt;Product&gt; products = query.getResultList();

        for (Product product : products) {
            System.out.println(&quot;Name: &quot; + product.getName() + &quot;, Price: &quot; + product.getPrice());
        }

        em.close();
        emf.close();
    }

}" style="color:#e1e4e8;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki github-dark" style="background-color: #24292e" tabindex="0"><code><span class="line"><span style="color: #F97583">import</span><span style="color: #E1E4E8"> jakarta.persistence.TypedQuery;</span></span>
<span class="line"><span style="color: #F97583">import</span><span style="color: #E1E4E8"> java.util.List;</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F97583">public</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">class</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">Main</span><span style="color: #E1E4E8"> {</span></span>
<span class="line"></span>
<span class="line"><span style="color: #E1E4E8">    </span><span style="color: #F97583">public</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">static</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">void</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">main</span><span style="color: #E1E4E8">(</span><span style="color: #F97583">String</span><span style="color: #E1E4E8">[] </span><span style="color: #FFAB70">args</span><span style="color: #E1E4E8">) {</span></span>
<span class="line"><span style="color: #E1E4E8">        EntityManagerFactory emf </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> Persistence.</span><span style="color: #B392F0">createEntityManagerFactory</span><span style="color: #E1E4E8">(</span><span style="color: #9ECBFF">&quot;my-persistence-unit&quot;</span><span style="color: #E1E4E8">);</span></span>
<span class="line"><span style="color: #E1E4E8">        EntityManager em </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> emf.</span><span style="color: #B392F0">createEntityManager</span><span style="color: #E1E4E8">();</span></span>
<span class="line"></span>
<span class="line"><span style="color: #E1E4E8">        </span><span style="color: #6A737D">// Querying products by category</span></span>
<span class="line"><span style="color: #E1E4E8">        String jpql </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> </span><span style="color: #9ECBFF">&quot;SELECT p FROM Product p WHERE p.category = :category&quot;</span><span style="color: #E1E4E8">;</span></span>
<span class="line"><span style="color: #E1E4E8">        TypedQuery&lt;</span><span style="color: #F97583">Product</span><span style="color: #E1E4E8">&gt; query </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> em.</span><span style="color: #B392F0">createQuery</span><span style="color: #E1E4E8">(jpql, Product.class);</span></span>
<span class="line"><span style="color: #E1E4E8">        query.</span><span style="color: #B392F0">setParameter</span><span style="color: #E1E4E8">(</span><span style="color: #9ECBFF">&quot;category&quot;</span><span style="color: #E1E4E8">, </span><span style="color: #9ECBFF">&quot;Electronics&quot;</span><span style="color: #E1E4E8">);</span></span>
<span class="line"></span>
<span class="line"><span style="color: #E1E4E8">        List&lt;</span><span style="color: #F97583">Product</span><span style="color: #E1E4E8">&gt; products </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> query.</span><span style="color: #B392F0">getResultList</span><span style="color: #E1E4E8">();</span></span>
<span class="line"></span>
<span class="line"><span style="color: #E1E4E8">        </span><span style="color: #F97583">for</span><span style="color: #E1E4E8"> (Product product </span><span style="color: #F97583">:</span><span style="color: #E1E4E8"> products) {</span></span>
<span class="line"><span style="color: #E1E4E8">            System.out.</span><span style="color: #B392F0">println</span><span style="color: #E1E4E8">(</span><span style="color: #9ECBFF">&quot;Name: &quot;</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">+</span><span style="color: #E1E4E8"> product.</span><span style="color: #B392F0">getName</span><span style="color: #E1E4E8">() </span><span style="color: #F97583">+</span><span style="color: #E1E4E8"> </span><span style="color: #9ECBFF">&quot;, Price: &quot;</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">+</span><span style="color: #E1E4E8"> product.</span><span style="color: #B392F0">getPrice</span><span style="color: #E1E4E8">());</span></span>
<span class="line"><span style="color: #E1E4E8">        }</span></span>
<span class="line"></span>
<span class="line"><span style="color: #E1E4E8">        em.</span><span style="color: #B392F0">close</span><span style="color: #E1E4E8">();</span></span>
<span class="line"><span style="color: #E1E4E8">        emf.</span><span style="color: #B392F0">close</span><span style="color: #E1E4E8">();</span></span>
<span class="line"><span style="color: #E1E4E8">    }</span></span>
<span class="line"></span>
<span class="line"><span style="color: #E1E4E8">}</span></span></code></pre></div>



<p>In this code, we define a JPQL query to select all products with a specific category. We use TypedQuery to specify the return type of the query. The query parameters are bound <code>using query.setParameter()</code>, and the results are obtained using <code>query.getResultList()</code>.</p>



<h2 class="wp-block-heading">IV. Managing Transactions in JPA</h2>



<p>JPA provides built-in support for managing transactions, ensuring data integrity and consistency in the database.</p>



<h3 class="wp-block-heading">A. Transactional Operations</h3>



<p>By default, JPA uses container-managed transactions, meaning that transactions are managed by the application server or container in a Java EE environment. However, in Java SE or non-container environments, developers can manage transactions programmatically using the <code>EntityManager</code>.</p>



<div class="wp-block-kevinbatdorf-code-block-pro" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:clamp(14px, .875rem, 21px);font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:clamp(20px, 1.25rem, 30px);--cbp-tab-width:4;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:10px 0px 10px 16px;margin-bottom:-2px;width:100%;text-align:left;background-color:#2f363c;color:#d3d7dd">Java</span><span role="button" tabindex="0" data-code="public class Main {

    public static void main(String[] args) {
        EntityManagerFactory emf = Persistence.createEntityManagerFactory(&quot;my-persistence-unit&quot;);
        EntityManager em = emf.createEntityManager();

        try {
            // Starting a new transaction
            em.getTransaction().begin();

            // Persisting or updating entities

            // Committing the transaction
            em.getTransaction().commit();
        } catch (Exception e) {
            // Handling exceptions and rolling back the transaction if necessary
            em.getTransaction().rollback();
        } finally {
            // Closing the EntityManager
            em.close();
        }

        emf.close();
    }

}" style="color:#e1e4e8;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki github-dark" style="background-color: #24292e" tabindex="0"><code><span class="line"><span style="color: #F97583">public</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">class</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">Main</span><span style="color: #E1E4E8"> {</span></span>
<span class="line"></span>
<span class="line"><span style="color: #E1E4E8">    </span><span style="color: #F97583">public</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">static</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">void</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">main</span><span style="color: #E1E4E8">(</span><span style="color: #F97583">String</span><span style="color: #E1E4E8">[] </span><span style="color: #FFAB70">args</span><span style="color: #E1E4E8">) {</span></span>
<span class="line"><span style="color: #E1E4E8">        EntityManagerFactory emf </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> Persistence.</span><span style="color: #B392F0">createEntityManagerFactory</span><span style="color: #E1E4E8">(</span><span style="color: #9ECBFF">&quot;my-persistence-unit&quot;</span><span style="color: #E1E4E8">);</span></span>
<span class="line"><span style="color: #E1E4E8">        EntityManager em </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> emf.</span><span style="color: #B392F0">createEntityManager</span><span style="color: #E1E4E8">();</span></span>
<span class="line"></span>
<span class="line"><span style="color: #E1E4E8">        </span><span style="color: #F97583">try</span><span style="color: #E1E4E8"> {</span></span>
<span class="line"><span style="color: #E1E4E8">            </span><span style="color: #6A737D">// Starting a new transaction</span></span>
<span class="line"><span style="color: #E1E4E8">            em.</span><span style="color: #B392F0">getTransaction</span><span style="color: #E1E4E8">().</span><span style="color: #B392F0">begin</span><span style="color: #E1E4E8">();</span></span>
<span class="line"></span>
<span class="line"><span style="color: #E1E4E8">            </span><span style="color: #6A737D">// Persisting or updating entities</span></span>
<span class="line"></span>
<span class="line"><span style="color: #E1E4E8">            </span><span style="color: #6A737D">// Committing the transaction</span></span>
<span class="line"><span style="color: #E1E4E8">            em.</span><span style="color: #B392F0">getTransaction</span><span style="color: #E1E4E8">().</span><span style="color: #B392F0">commit</span><span style="color: #E1E4E8">();</span></span>
<span class="line"><span style="color: #E1E4E8">        } </span><span style="color: #F97583">catch</span><span style="color: #E1E4E8"> (Exception </span><span style="color: #FFAB70">e</span><span style="color: #E1E4E8">) {</span></span>
<span class="line"><span style="color: #E1E4E8">            </span><span style="color: #6A737D">// Handling exceptions and rolling back the transaction if necessary</span></span>
<span class="line"><span style="color: #E1E4E8">            em.</span><span style="color: #B392F0">getTransaction</span><span style="color: #E1E4E8">().</span><span style="color: #B392F0">rollback</span><span style="color: #E1E4E8">();</span></span>
<span class="line"><span style="color: #E1E4E8">        } </span><span style="color: #F97583">finally</span><span style="color: #E1E4E8"> {</span></span>
<span class="line"><span style="color: #E1E4E8">            </span><span style="color: #6A737D">// Closing the EntityManager</span></span>
<span class="line"><span style="color: #E1E4E8">            em.</span><span style="color: #B392F0">close</span><span style="color: #E1E4E8">();</span></span>
<span class="line"><span style="color: #E1E4E8">        }</span></span>
<span class="line"></span>
<span class="line"><span style="color: #E1E4E8">        emf.</span><span style="color: #B392F0">close</span><span style="color: #E1E4E8">();</span></span>
<span class="line"><span style="color: #E1E4E8">    }</span></span>
<span class="line"></span>
<span class="line"><span style="color: #E1E4E8">}</span></span></code></pre></div>



<p>In this code, we wrap our database operations within a try-catch block. We start a new transaction with <code>em.getTransaction().begin()</code>, persist or update entities, and commit the transaction with <code>em.getTransaction().commit()</code>. If an exception occurs, the transaction is rolled back using <code>em.getTransaction().rollback()</code>. Finally, we close the EntityManager in the “finally” block.</p>



<h2 class="wp-block-heading">V. CRUD Operations</h2>



<p>For performing CRUD operations, you&#8217;ll have to manually manage the <code>EntityManager</code>.</p>



<p>Let&#8217;s assume the following entity class:</p>



<div class="wp-block-kevinbatdorf-code-block-pro" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:clamp(14px, .875rem, 21px);font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:clamp(20px, 1.25rem, 30px);--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:10px 0px 10px 16px;margin-bottom:-2px;width:100%;text-align:left;background-color:#2f363c;color:#d3d7dd">Java</span><span role="button" tabindex="0" data-code="import jakarta.persistence.Entity;
import jakarta.persistence.Id;

@Entity
public class Person {
    @Id
    private Long id;
    private String name;
    private int age;

    // Getters and setters
}" style="color:#e1e4e8;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki github-dark" style="background-color: #24292e" tabindex="0"><code><span class="line"><span style="color: #F97583">import</span><span style="color: #E1E4E8"> jakarta.persistence.Entity;</span></span>
<span class="line"><span style="color: #F97583">import</span><span style="color: #E1E4E8"> jakarta.persistence.Id;</span></span>
<span class="line"></span>
<span class="line"><span style="color: #E1E4E8">@</span><span style="color: #F97583">Entity</span></span>
<span class="line"><span style="color: #F97583">public</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">class</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">Person</span><span style="color: #E1E4E8"> {</span></span>
<span class="line"><span style="color: #E1E4E8">    @</span><span style="color: #F97583">Id</span></span>
<span class="line"><span style="color: #E1E4E8">    </span><span style="color: #F97583">private</span><span style="color: #E1E4E8"> Long id;</span></span>
<span class="line"><span style="color: #E1E4E8">    </span><span style="color: #F97583">private</span><span style="color: #E1E4E8"> String name;</span></span>
<span class="line"><span style="color: #E1E4E8">    </span><span style="color: #F97583">private</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">int</span><span style="color: #E1E4E8"> age;</span></span>
<span class="line"></span>
<span class="line"><span style="color: #E1E4E8">    </span><span style="color: #6A737D">// Getters and setters</span></span>
<span class="line"><span style="color: #E1E4E8">}</span></span></code></pre></div>



<p>Initialize EntityManager:</p>



<div class="wp-block-kevinbatdorf-code-block-pro" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:clamp(14px, .875rem, 21px);font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:clamp(20px, 1.25rem, 30px);--cbp-tab-width:4;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:10px 0px 10px 16px;margin-bottom:-2px;width:100%;text-align:left;background-color:#2f363c;color:#d3d7dd">Java</span><span role="button" tabindex="0" data-code="import jakarta.persistence.Persistence;
import jakarta.persistence.EntityManager;

EntityManager entityManager = Persistence.createEntityManagerFactory(&quot;myPU&quot;).createEntityManager();" style="color:#e1e4e8;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki github-dark" style="background-color: #24292e" tabindex="0"><code><span class="line"><span style="color: #F97583">import</span><span style="color: #E1E4E8"> jakarta.persistence.Persistence;</span></span>
<span class="line"><span style="color: #F97583">import</span><span style="color: #E1E4E8"> jakarta.persistence.EntityManager;</span></span>
<span class="line"></span>
<span class="line"><span style="color: #E1E4E8">EntityManager entityManager </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> Persistence.</span><span style="color: #B392F0">createEntityManagerFactory</span><span style="color: #E1E4E8">(</span><span style="color: #9ECBFF">&quot;myPU&quot;</span><span style="color: #E1E4E8">).</span><span style="color: #B392F0">createEntityManager</span><span style="color: #E1E4E8">();</span></span></code></pre></div>



<h3 class="wp-block-heading">Create (Insert)</h3>



<div class="wp-block-kevinbatdorf-code-block-pro" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:clamp(14px, .875rem, 21px);font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:clamp(20px, 1.25rem, 30px);--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:10px 0px 10px 16px;margin-bottom:-2px;width:100%;text-align:left;background-color:#2f363c;color:#d3d7dd">Java</span><span role="button" tabindex="0" data-code="entityManager.getTransaction().begin();
Person person = new Person();
person.setId(1L);
person.setName(&quot;John&quot;);
person.setAge(30);
entityManager.persist(person);
entityManager.getTransaction().commit();" style="color:#e1e4e8;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki github-dark" style="background-color: #24292e" tabindex="0"><code><span class="line"><span style="color: #E1E4E8">entityManager.</span><span style="color: #B392F0">getTransaction</span><span style="color: #E1E4E8">().</span><span style="color: #B392F0">begin</span><span style="color: #E1E4E8">();</span></span>
<span class="line"><span style="color: #E1E4E8">Person person </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">new</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">Person</span><span style="color: #E1E4E8">();</span></span>
<span class="line"><span style="color: #E1E4E8">person.</span><span style="color: #B392F0">setId</span><span style="color: #E1E4E8">(</span><span style="color: #79B8FF">1L</span><span style="color: #E1E4E8">);</span></span>
<span class="line"><span style="color: #E1E4E8">person.</span><span style="color: #B392F0">setName</span><span style="color: #E1E4E8">(</span><span style="color: #9ECBFF">&quot;John&quot;</span><span style="color: #E1E4E8">);</span></span>
<span class="line"><span style="color: #E1E4E8">person.</span><span style="color: #B392F0">setAge</span><span style="color: #E1E4E8">(</span><span style="color: #79B8FF">30</span><span style="color: #E1E4E8">);</span></span>
<span class="line"><span style="color: #E1E4E8">entityManager.</span><span style="color: #B392F0">persist</span><span style="color: #E1E4E8">(person);</span></span>
<span class="line"><span style="color: #E1E4E8">entityManager.</span><span style="color: #B392F0">getTransaction</span><span style="color: #E1E4E8">().</span><span style="color: #B392F0">commit</span><span style="color: #E1E4E8">();</span></span></code></pre></div>



<h3 class="wp-block-heading">Read (Select)</h3>



<div class="wp-block-kevinbatdorf-code-block-pro" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:clamp(14px, .875rem, 21px);font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:clamp(20px, 1.25rem, 30px);--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:10px 0px 10px 16px;margin-bottom:-2px;width:100%;text-align:left;background-color:#2f363c;color:#d3d7dd">Java</span><span role="button" tabindex="0" data-code="Person person = entityManager.find(Person.class, 1L);" style="color:#e1e4e8;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki github-dark" style="background-color: #24292e" tabindex="0"><code><span class="line"><span style="color: #E1E4E8">Person person </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> entityManager.</span><span style="color: #B392F0">find</span><span style="color: #E1E4E8">(Person.class, </span><span style="color: #79B8FF">1L</span><span style="color: #E1E4E8">);</span></span></code></pre></div>



<h3 class="wp-block-heading">Update</h3>



<div class="wp-block-kevinbatdorf-code-block-pro" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:clamp(14px, .875rem, 21px);font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:clamp(20px, 1.25rem, 30px);--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:10px 0px 10px 16px;margin-bottom:-2px;width:100%;text-align:left;background-color:#2f363c;color:#d3d7dd">Java</span><span role="button" tabindex="0" data-code="entityManager.getTransaction().begin();
Person person = entityManager.find(Person.class, 1L);
person.setAge(31);
entityManager.merge(person);
entityManager.getTransaction().commit();" style="color:#e1e4e8;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki github-dark" style="background-color: #24292e" tabindex="0"><code><span class="line"><span style="color: #E1E4E8">entityManager.</span><span style="color: #B392F0">getTransaction</span><span style="color: #E1E4E8">().</span><span style="color: #B392F0">begin</span><span style="color: #E1E4E8">();</span></span>
<span class="line"><span style="color: #E1E4E8">Person person </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> entityManager.</span><span style="color: #B392F0">find</span><span style="color: #E1E4E8">(Person.class, </span><span style="color: #79B8FF">1L</span><span style="color: #E1E4E8">);</span></span>
<span class="line"><span style="color: #E1E4E8">person.</span><span style="color: #B392F0">setAge</span><span style="color: #E1E4E8">(</span><span style="color: #79B8FF">31</span><span style="color: #E1E4E8">);</span></span>
<span class="line"><span style="color: #E1E4E8">entityManager.</span><span style="color: #B392F0">merge</span><span style="color: #E1E4E8">(person);</span></span>
<span class="line"><span style="color: #E1E4E8">entityManager.</span><span style="color: #B392F0">getTransaction</span><span style="color: #E1E4E8">().</span><span style="color: #B392F0">commit</span><span style="color: #E1E4E8">();</span></span></code></pre></div>



<h3 class="wp-block-heading">Delete</h3>



<div class="wp-block-kevinbatdorf-code-block-pro" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:clamp(14px, .875rem, 21px);font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:clamp(20px, 1.25rem, 30px);--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:10px 0px 10px 16px;margin-bottom:-2px;width:100%;text-align:left;background-color:#2f363c;color:#d3d7dd">Java</span><span role="button" tabindex="0" data-code="entityManager.getTransaction().begin();
Person person = entityManager.find(Person.class, 1L);
entityManager.remove(person);
entityManager.getTransaction().commit();" style="color:#e1e4e8;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki github-dark" style="background-color: #24292e" tabindex="0"><code><span class="line"><span style="color: #E1E4E8">entityManager.</span><span style="color: #B392F0">getTransaction</span><span style="color: #E1E4E8">().</span><span style="color: #B392F0">begin</span><span style="color: #E1E4E8">();</span></span>
<span class="line"><span style="color: #E1E4E8">Person person </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> entityManager.</span><span style="color: #B392F0">find</span><span style="color: #E1E4E8">(Person.class, </span><span style="color: #79B8FF">1L</span><span style="color: #E1E4E8">);</span></span>
<span class="line"><span style="color: #E1E4E8">entityManager.</span><span style="color: #B392F0">remove</span><span style="color: #E1E4E8">(person);</span></span>
<span class="line"><span style="color: #E1E4E8">entityManager.</span><span style="color: #B392F0">getTransaction</span><span style="color: #E1E4E8">().</span><span style="color: #B392F0">commit</span><span style="color: #E1E4E8">();</span></span></code></pre></div>



<p>Now you&#8217;ve set up a basic CRUD application using plain JPA. You&#8217;ll have to manually manage transaction boundaries and other low-level details, which is one of the reasons frameworks like Spring are often used. Nonetheless, this guide should give you a good starting point for how to use JPA directly.</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<p>Java Persistence API (JPA) is a powerful and user-friendly ORM framework that simplifies database interactions in Java applications. By using JPA’s annotations, entity classes, and EntityManager, developers can seamlessly map Java objects to relational databases, perform database operations, and manage transactions with ease.</p>



<p>In this beginner’s guide, we covered the essential concepts of JPA, from creating entity classes and mapping annotations to persisting and querying data. Armed with this knowledge, you are now well-equipped to dive deeper into the world of JPA, explore its advanced features, and build sophisticated, database-driven Java applications. So, embrace the power of JPA, and unlock a new level of simplicity and efficiency in your Java development journey.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Unleashing the Power of a Versatile Language</title>
		<link>https://blog.j-dev.app/unleashing-the-power-of-a-versatile-language/</link>
		
		<dc:creator><![CDATA[JuanC]]></dc:creator>
		<pubDate>Sat, 12 Aug 2023 05:59:54 +0000</pubDate>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Programming]]></category>
		<guid isPermaLink="false">https://blog.j-dev.app/?page_id=51</guid>

					<description><![CDATA[In the ever-evolving landscape of computer science and software development, Java remains an indomitable force. Renowned for its versatility, stability, and platform independence, Java has shaped the digital world for decades. This article delves into the intricacies of Java programming, unveiling its fundamental concepts, exploring its unique features, and showcasing its widespread applications. Whether you [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p>In the ever-evolving landscape of computer science and software development, Java remains an indomitable force. Renowned for its versatility, stability, and platform independence, Java has shaped the digital world for decades. This article delves into the intricacies of Java programming, unveiling its fundamental concepts, exploring its unique features, and showcasing its widespread applications. Whether you are an aspiring developer seeking to enter the realm of coding or an accomplished programmer looking to broaden your expertise, join us on this enthralling journey as we unravel the wonders of Java.</p>



<h2 class="wp-block-heading">I. The Foundation of Java: Object-Oriented Paradigm</h2>



<p>Java’s foundation lies in its object-oriented paradigm, which is the bedrock of modern programming. By embracing objects and classes, Java empowers developers to create reusable, modular, and scalable code. <a rel="noreferrer noopener" href="https://en.wikipedia.org/wiki/Object-oriented_programming" target="_blank">Object-oriented programming</a> (OOP) embodies the principles of encapsulation, inheritance, polymorphism, and abstraction, enabling programmers to model real-world entities in a structured manner.</p>



<h3 class="wp-block-heading">A. Understanding Objects and Classes</h3>



<p>In Java, objects represent tangible entities, while classes serve as blueprints for creating these objects. The interplay of classes and objects fosters code re-usability and promotes the efficient organization of software components. Each object encapsulates its state (data) and behavior (methods), and through careful design, developers can ensure that objects interact with each other seamlessly.</p>



<p>When defining classes, developers determine the attributes and behaviors shared by the objects of that class. <a href="https://en.wikipedia.org/wiki/Encapsulation_(computer_programming)" target="_blank" rel="noreferrer noopener">Encapsulation</a>, an essential aspect of OOP, shields the internal details of a class from the external world, ensuring that objects interact only through well-defined interfaces. This approach enhances code maintainability and reduces the risk of unintended side effects.</p>



<figure class="wp-block-image size-full"><img fetchpriority="high" decoding="async" width="1024" height="1024" src="https://blog.j-dev.app/wp-content/uploads/2023/08/web2b.jpg" alt="" class="wp-image-6" style="aspect-ratio:4/3;object-fit:cover" srcset="https://blog.j-dev.app/wp-content/uploads/2023/08/web2b.jpg 1024w, https://blog.j-dev.app/wp-content/uploads/2023/08/web2b-300x300.jpg 300w, https://blog.j-dev.app/wp-content/uploads/2023/08/web2b-150x150.jpg 150w, https://blog.j-dev.app/wp-content/uploads/2023/08/web2b-768x768.jpg 768w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<h3 class="wp-block-heading">B. Mastering Inheritance and Polymorphism</h3>



<p>Inheritance, a core tenet of OOP, allows classes to derive properties and behaviors from other classes. By creating a new class from an existing one, developers can reuse the features of the parent class and extend its functionality. This hierarchical relationship between classes fosters code organization and enhances code readability.</p>



<p><a href="https://en.wikipedia.org/wiki/Polymorphism_(computer_science)" target="_blank" rel="noreferrer noopener">Polymorphism</a>, a Greek word meaning “many forms,” enables objects to assume multiple forms and behave differently based on their context. The two primary types of polymorphism in Java are compile-time (method overloading) and runtime (method overriding). Method overloading allows multiple methods with the same name but different parameter lists, while method overriding allows a subclass to provide a specific implementation of a method already defined in its superclass.</p>



<h3 class="wp-block-heading">C. Embracing Abstraction for Elegance</h3>



<p>Abstraction empowers programmers to focus on essential attributes while hiding intricate implementation details. Java’s abstraction mechanisms facilitate the creation of clear and concise code, elevating the readability and maintainability of projects. Abstract classes and interfaces play a pivotal role in achieving abstraction.</p>



<p>Abstract classes act as a blueprint for other classes, allowing them to define common attributes and methods. However, abstract classes cannot be instantiated directly; they serve as a foundation for subclasses to extend and implement their specific functionalities. Interfaces, on the other hand, define contracts that classes must adhere to, specifying method signatures without implementation details. A class can implement multiple interfaces, enabling developers to achieve multiple inheritances through interfaces.</p>



<p>Implementing abstraction encourages a modular approach, where each class focuses on a specific task, making the codebase more maintainable and adaptable to changes. Moreover, abstraction plays a crucial role in designing frameworks and libraries, as it allows developers to provide generic solutions that can be customized by other programmers.</p>



<figure class="wp-block-image size-full"><img decoding="async" width="1024" height="1024" src="https://blog.j-dev.app/wp-content/uploads/2023/08/web3b.jpg" alt="" class="wp-image-8" style="aspect-ratio:4/3;object-fit:cover" srcset="https://blog.j-dev.app/wp-content/uploads/2023/08/web3b.jpg 1024w, https://blog.j-dev.app/wp-content/uploads/2023/08/web3b-300x300.jpg 300w, https://blog.j-dev.app/wp-content/uploads/2023/08/web3b-150x150.jpg 150w, https://blog.j-dev.app/wp-content/uploads/2023/08/web3b-768x768.jpg 768w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<h2 class="wp-block-heading">II. Harnessing the Power of Java Libraries and APIs</h2>



<p>The Java ecosystem boasts a rich assortment of libraries and <a rel="noreferrer noopener" href="https://en.wikipedia.org/wiki/API" target="_blank">Application Programming Interfaces</a> (APIs) that expedite development and extend the language’s capabilities. These libraries cover a vast array of domains, ranging from GUI development and database connectivity to networking and cryptography.</p>



<h3 class="wp-block-heading">A. Streamlining Development with Standard Libraries</h3>



<p>Java’s standard library encompasses a treasure trove of pre-built classes and methods, carefully curated to handle common programming tasks. From data structures like arrays, lists, and maps to input/output operations and multi-threading, the standard library provides essential tools for developers to streamline their projects.</p>



<p>One of the most prominent features of the standard library is the <a href="https://docs.oracle.com/javase/8/docs/technotes/guides/collections/overview.html" target="_blank" rel="noreferrer noopener">Collections Framework</a>, which offers a comprehensive set of interfaces and classes for handling collections of objects, such as lists, sets, and queues. The Collections Framework employs generics, a feature introduced in Java 5, to ensure type safety and enhance code readability.</p>



<p>Additionally, the standard library includes utilities for handling dates and times, managing exceptions, working with regular expressions, and more. By leveraging these ready-made components, developers can focus on implementing business logic rather than reinventing the wheel, ultimately accelerating development and improving code quality.</p>



<h3 class="wp-block-heading">B. Exploring Third-party Libraries</h3>



<p>Beyond the standard library, Java developers can tap into an extensive selection of third-party libraries tailored for specific needs. These libraries, often open-source and actively maintained by the community, enhance functionality and offer solutions to intricate challenges.</p>



<p>For instance, Apache Commons provides a plethora of reusable Java components that address common programming tasks, such as string manipulation, mathematical operations, and file management. Google Guava, on the other hand, extends the Collections Framework with additional utilities, functional programming support, and caching mechanisms.</p>



<p>Libraries like <a href="https://junit.org/" target="_blank" rel="noreferrer noopener">JUnit</a> facilitate automated testing, ensuring robustness and reliability in software projects. Similarly, frameworks like <a href="https://hibernate.org/" target="_blank" rel="noreferrer noopener">Hibernate</a> enable seamless interaction with databases through <a href="https://en.wikipedia.org/wiki/Object%E2%80%93relational_mapping" target="_blank" rel="noreferrer noopener">Object-Relational Mapping</a> (ORM), abstracting away the complexities of SQL queries and database management.</p>



<p>By incorporating third-party libraries into their projects, developers can capitalize on the collective expertise of the Java community, saving time and effort while delivering high-quality applications.</p>



<h3 class="wp-block-heading">C. Interacting with Java APIs</h3>



<p>APIs provide a structured interface for communication between different software components. Java’s APIs facilitate interaction with system functionalities, databases, web services, and more. Understanding how to leverage these APIs effectively is crucial for unlocking the full potential of Java programming.</p>



<p>Java’s standard API includes a diverse range of packages, from <em>java.io</em> for input/output operations to <em>java.net</em> for networking. The <em>java.sql</em> package provides the necessary classes and interfaces for working with relational databases, while the <em>javax.swing</em> package allows developers to create Graphical User Interfaces (GUIs) for desktop applications.</p>



<p>Moreover, Java has embraced the world of web services with the <a href="https://www.oracle.com/technical-resources/articles/java/jax-rs.html" target="_blank" rel="noreferrer noopener">Java API for RESTful Web Services</a> (JAX-RS) and <a rel="noreferrer noopener" href="https://docs.oracle.com/javase/8/docs/technotes/guides/xml/jax-ws/index.html" target="_blank">Java API for XML Web Services</a> (JAX-WS). These APIs facilitate the creation and consumption of web services, enabling seamless communication between different software systems over the internet.</p>



<p>In recent years, Java’s APIs have evolved to accommodate cloud computing and <a href="https://microservices.io/patterns/microservices.html" target="_blank" rel="noreferrer noopener">microservices architecture</a>. APIs like <a href="https://projects.eclipse.org/projects/ee4j.jpa" data-type="link" data-id="https://projects.eclipse.org/projects/ee4j.jpa" target="_blank" rel="noreferrer noopener">Jakarta Persistence</a>, previously known as Java Persistence API (JPA), and <a href="https://www.oracle.com/technical-resources/articles/java/json.html" target="_blank" rel="noreferrer noopener">Java API for JSON Processing</a> (JSON-P) cater to these modern paradigms, enabling developers to build scalable and flexible applications.</p>



<figure class="wp-block-image size-full"><img decoding="async" width="1024" height="1024" src="https://blog.j-dev.app/wp-content/uploads/2023/08/web4b.jpg" alt="" class="wp-image-9" style="aspect-ratio:4/3;object-fit:cover" srcset="https://blog.j-dev.app/wp-content/uploads/2023/08/web4b.jpg 1024w, https://blog.j-dev.app/wp-content/uploads/2023/08/web4b-300x300.jpg 300w, https://blog.j-dev.app/wp-content/uploads/2023/08/web4b-150x150.jpg 150w, https://blog.j-dev.app/wp-content/uploads/2023/08/web4b-768x768.jpg 768w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<h2 class="wp-block-heading">III. Java in Practice: Real-world Applications and Future Prospects</h2>



<p>Java’s adaptability has led to its widespread adoption in a myriad of domains, from web development and mobile applications to enterprise solutions and embedded systems. As technology continues to evolve, Java remains steadfast and shows promising prospects in shaping the future of software development.</p>



<h3 class="wp-block-heading">A. Java in the Web Development Landscape</h3>



<p>Java’s presence in web development is pervasive, with frameworks like <a rel="noreferrer noopener" href="https://spring.io/" target="_blank">Spring</a> and <a href="https://www.oracle.com/java/technologies/javaserverfaces.html" target="_blank" rel="noreferrer noopener">JavaServer Faces</a> (JSF) empowering developers to build feature-rich web applications. The Spring Framework, in particular, offers a comprehensive suite of tools and modules for building enterprise-level applications. Its dependency injection mechanism, coupled with robust support for various architectural patterns, enhances code maintainability and promotes best practices in development.</p>



<p>JSF, on the other hand, simplifies the creation of user interfaces by providing a component-based model, allowing developers to assemble complex web pages with reusable and customizable components. By combining JavaServer Faces with <a href="https://www.oracle.com/java/technologies/jspt.html" target="_blank" rel="noreferrer noopener">JavaServer Pages</a> (JSP) and Enterprise <a rel="noreferrer noopener" href="https://docs.oracle.com/javase/8/docs/technotes/guides/beans/index.html" target="_blank">JavaBeans</a> (EJB), developers can build enterprise-grade applications catering to diverse business requirements.</p>



<h3 class="wp-block-heading">B. Java in Mobile App Development</h3>



<p>With the rise of Android, Java has become the de facto language for developing mobile applications. Java, alongside the Android Software Development Kit (SDK), enables developers to create engaging and feature-rich applications for smartphones and tablets.</p>



<p>Android’s robust architecture, coupled with Java’s versatility, allows developers to harness hardware capabilities and create innovative applications that seamlessly integrate with the mobile ecosystem. From multimedia-rich applications to location-based services and augmented reality experiences, Java remains at the heart of Android development.</p>



<p>The advent of <a href="https://kotlinlang.org/" target="_blank" rel="noreferrer noopener">Kotlin</a>, a language designed for Android development, has also influenced the mobile development landscape. While Kotlin provides improved syntax and enhanced safety features, Java continues to be a strong contender for building Android applications, especially for those developers who already possess Java expertise.</p>



<h3 class="wp-block-heading">C. Java for Scalable Enterprise Solutions</h3>



<p>Java’s robustness and scalability make it an ideal choice for crafting large-scale enterprise solutions. From <a href="https://en.wikipedia.org/wiki/Customer_relationship_management" target="_blank" rel="noreferrer noopener">Customer Relationship Management</a> (CRM) systems to <a href="https://en.wikipedia.org/wiki/Big_data" target="_blank" rel="noreferrer noopener">Big Data</a> processing, Java powers a wide spectrum of mission-critical applications.</p>



<p>In the realm of server-side development, Java’s versatility is showcased through frameworks like JavaServer Pages (JSP), Java Servlets, and the aforementioned Spring Framework. These technologies allow developers to build scalable web applications and <a href="https://en.wikipedia.org/wiki/Representational_state_transfer" target="_blank" rel="noreferrer noopener">RESTful</a> services, capable of handling a high volume of concurrent requests.</p>



<p>Enterprise JavaBeans (EJBs) play a crucial role in developing distributed applications. EJBs provide a component-based model that simplifies the development of distributed, transactional, and secure applications for Java Enterprise Edition (EE) environments.</p>



<p>Moreover, Java’s integration with Big Data technologies, such as <a href="https://hadoop.apache.org/" target="_blank" rel="noreferrer noopener">Apache Hadoop</a> and <a href="https://spark.apache.org/" target="_blank" rel="noreferrer noopener">Apache Spark</a>, reinforces its position as a potent tool for processing and analyzing vast datasets. Java’s ability to parallelize computations and its support for distributed computing enable seamless data processing in large-scale, data-intensive applications.</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<p>Java programming stands as a timeless art form, with its object-oriented paradigm, powerful libraries, and diverse applications. In this article, we have traversed the many facets of Java’s capabilities, from the intricacies of object-oriented programming to the vast landscape of libraries, APIs, and real-world applications.</p>



<p>The journey into Java programming continues to be an enriching one, as its versatility and adaptability keep it relevant in the rapidly evolving world of technology. Whether you are a seasoned programmer or an aspiring enthusiast, mastering Java opens doors to an ever-expanding universe of opportunities in the realm of computer science and beyond. So, pick up your IDE, embrace the elegance of Java, and let your imagination and code intertwine to create innovative solutions for the world of tomorrow.</p>
]]></content:encoded>
					
		
		
			</item>
	</channel>
</rss>
