<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Sachin Sarawgi on Medium]]></title>
        <description><![CDATA[Stories by Sachin Sarawgi on Medium]]></description>
        <link>https://medium.com/@codesprintpro?source=rss-295538043760------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*AWtVrtn3W7PSMvz7EJ5fCQ.jpeg</url>
            <title>Stories by Sachin Sarawgi on Medium</title>
            <link>https://medium.com/@codesprintpro?source=rss-295538043760------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 11:19:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@codesprintpro/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Part 5 Real-World Applications and Best Practices with Java Streams]]></title>
            <link>https://medium.com/@codesprintpro/part-5-real-world-applications-and-best-practices-with-java-streams-26b4fa04db12?source=rss-295538043760------2</link>
            <guid isPermaLink="false">https://medium.com/p/26b4fa04db12</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Sachin Sarawgi]]></dc:creator>
            <pubDate>Thu, 16 Jan 2025 10:34:14 GMT</pubDate>
            <atom:updated>2025-01-16T10:34:14.302Z</atom:updated>
            <content:encoded><![CDATA[<p>Welcome to the final part of our Java Streams series! So far, we’ve covered the basics of streams, intermediate operations, terminal operations, debugging techniques, and optimization strategies. In this installment, we’ll focus on real-world applications of Java Streams and the best practices to follow when designing stream pipelines. By the end of this blog, you’ll be equipped to apply Java Streams effectively in professional projects.</p><h3><strong>1. Real-World Applications of Java Streams</strong></h3><p>Streams excel in scenarios where data needs to be transformed, filtered, or aggregated. Here are some practical applications:</p><h4>1.1 Processing Large Data Sets</h4><p>Streams simplify the analysis of large data sets by enabling efficient filtering and aggregation.<br><strong>Example: Analyzing Sales Data</strong></p><pre>import java.util.List;<br>import java.util.Map;<br>import java.util.stream.Collectors;<br><br>public class SalesAnalysis {<br>    static class Sale {<br>        String region;<br>        String product;<br>        double revenue;<br><br>        Sale(String region, String product, double revenue) {<br>            this.region = region;<br>            this.product = product;<br>            this.revenue = revenue;<br>        }<br>    }<br><br>    public static void main(String[] args) {<br>        List&lt;Sale&gt; sales = List.of(<br>            new Sale(&quot;North&quot;, &quot;Laptop&quot;, 1200.50),<br>            new Sale(&quot;South&quot;, &quot;Phone&quot;, 800.00),<br>            new Sale(&quot;North&quot;, &quot;Tablet&quot;, 600.00),<br>            new Sale(&quot;South&quot;, &quot;Laptop&quot;, 1500.00)<br>        );<br><br>        // Group sales by region and calculate total revenue<br>        Map&lt;String, Double&gt; totalRevenueByRegion = sales.stream()<br>            .collect(Collectors.groupingBy(<br>                sale -&gt; sale.region,<br>                Collectors.summingDouble(sale -&gt; sale.revenue)<br>            ));<br><br>        System.out.println(totalRevenueByRegion);<br>        // Output: {North=1800.5, South=2300.0}<br>    }<br>}</pre><h4>1.2 Building APIs with Aggregations</h4><p>Streams are useful for implementing backend APIs that require dynamic data processing.<br><strong>Example: Filtering and Sorting Products</strong></p><pre>import java.util.List;<br>import java.util.stream.Collectors;<br><br>public class ProductAPI {<br>    static class Product {<br>        String name;<br>        double price;<br><br>        Product(String name, double price) {<br>            this.name = name;<br>            this.price = price;<br>        }<br><br>        @Override<br>        public String toString() {<br>            return name + &quot; ($&quot; + price + &quot;)&quot;;<br>        }<br>    }<br><br>    public static void main(String[] args) {<br>        List&lt;Product&gt; products = List.of(<br>            new Product(&quot;Laptop&quot;, 1200.00),<br>            new Product(&quot;Phone&quot;, 800.00),<br>            new Product(&quot;Tablet&quot;, 600.00)<br>        );<br><br>        // Filter products by price and sort by name<br>        List&lt;Product&gt; filteredProducts = products.stream()<br>            .filter(product -&gt; product.price &gt; 700)<br>            .sorted((p1, p2) -&gt; p1.name.compareTo(p2.name))<br>            .collect(Collectors.toList());<br><br>        System.out.println(filteredProducts);<br>        // Output: [Laptop ($1200.0), Phone ($800.0)]<br>    }<br>}</pre><h4>1.3 Handling Nested Data Structures</h4><p>Streams make it easy to flatten and process nested collections.<br><strong>Example: Extracting All Words from Nested Lists</strong></p><pre>import java.util.List;<br><br>public class NestedDataProcessing {<br>    public static void main(String[] args) {<br>        List&lt;List&lt;String&gt;&gt; nestedWords = List.of(<br>            List.of(&quot;hello&quot;, &quot;world&quot;),<br>            List.of(&quot;java&quot;, &quot;streams&quot;),<br>            List.of(&quot;functional&quot;, &quot;programming&quot;)<br>        );<br><br>        nestedWords.stream()<br>            .flatMap(List::stream)<br>            .forEach(System.out::println);<br>        // Output: hello, world, java, streams, functional, programming<br>    }<br>}</pre><h3><strong>2. Best Practices for Using Java Streams</strong></h3><h4>2.1 Keep Pipelines Readable</h4><p>Streams allow for chaining multiple operations, but overly complex pipelines can become hard to read. Break them into smaller steps when necessary.<br><strong>Example:</strong></p><pre>// Complex pipeline<br>List&lt;String&gt; result = data.stream()<br>    .filter(condition1)<br>    .map(transformation1)<br>    .filter(condition2)<br>    .map(transformation2)<br>    .collect(Collectors.toList());<br><br>// Refactored for clarity<br>Stream&lt;String&gt; filteredData = data.stream().filter(condition1);<br>Stream&lt;String&gt; transformedData = filteredData.map(transformation1).filter(condition2);<br>List&lt;String&gt; result = transformedData.map(transformation2).collect(Collectors.toList());</pre><h4>2.2 Avoid Modifying Data Sources</h4><p>Streams are designed to be functional and should not modify the underlying data source.<br><strong>Anti-Pattern:</strong></p><pre>list.stream().forEach(element -&gt; list.add(newElement)); // Leads to ConcurrentModificationException</pre><p><strong>Correct Approach:</strong></p><pre>List&lt;String&gt; newList = list.stream()<br>    .map(element -&gt; transform(element))<br>    .collect(Collectors.toList());</pre><h4>2.3 Use Parallel Streams Cautiously</h4><p>Parallel streams can improve performance for large datasets, but they may introduce overhead or thread-safety issues for smaller or I/O-bound tasks. Use them judiciously.</p><p><strong>When to Use Parallel Streams:</strong></p><ul><li>Large, CPU-intensive tasks (e.g., numerical calculations).</li><li>Tasks that don’t require synchronization.</li></ul><h4>2.4 Optimize for Performance</h4><ul><li>Use primitive streams (IntStream, DoubleStream) for numerical data to avoid boxing and unboxing overhead.</li><li>Short-circuit operations (findFirst, limit) to terminate pipelines early.</li><li>Avoid stateful operations (sorted, distinct) on very large streams unless necessary.</li></ul><h4>2.5 Test Your Streams</h4><p>Ensure streams behave as expected by writing unit tests for critical pipelines. Validate edge cases such as empty streams or streams with null elements.</p><h3><strong>3. Tools and Libraries Enhancing Streams</strong></h3><h4>3.1 StreamEx</h4><p>StreamEx is an enhanced Java Streams library offering additional functionality like grouping, joining, and more concise syntax.<br>Example:</p><pre>import one.util.streamex.StreamEx;<br><br>public class StreamExExample {<br>    public static void main(String[] args) {<br>        List&lt;String&gt; names = List.of(&quot;Alice&quot;, &quot;Bob&quot;, &quot;Charlie&quot;);<br>        String result = StreamEx.of(names).joining(&quot;, &quot;);<br>        System.out.println(result); // Output: Alice, Bob, Charlie<br>    }<br>}</pre><h4>3.2 jOOQ</h4><p>For database operations, jOOQ provides a stream-like API for SQL queries, integrating seamlessly with Java Streams.</p><p><strong>Key Takeaways</strong></p><ol><li>Java Streams shine in real-world scenarios like data processing, API development, and nested data handling.</li><li>Following best practices ensures your stream pipelines remain efficient, readable, and maintainable.</li><li>Explore libraries like StreamEx or jOOĸ to extend the functionality of streams.</li></ol><p><strong>Conclusion</strong><br>Java Streams offer an elegant way to process data declaratively, simplifying complex workflows and reducing boilerplate code. By mastering their applications and adhering to best practices, you can build robust and efficient software solutions. This concludes our Java Streams series. If you’ve found these blogs helpful, share them with your peers and let us know your feedback in the comments below!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=26b4fa04db12" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 4: Debugging and Optimizing Java Streams for Performance]]></title>
            <link>https://medium.com/@codesprintpro/part-4-debugging-and-optimizing-java-streams-for-performance-d1060bb6637c?source=rss-295538043760------2</link>
            <guid isPermaLink="false">https://medium.com/p/d1060bb6637c</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Sachin Sarawgi]]></dc:creator>
            <pubDate>Wed, 15 Jan 2025 08:56:20 GMT</pubDate>
            <atom:updated>2025-01-26T16:57:18.813Z</atom:updated>
            <content:encoded><![CDATA[<p>Welcome to the fourth part of our Java Streams series! In the previous parts, we explored how to create streams, use intermediate operations, and leverage terminal operations for real-world use cases. Now, let’s shift our focus to debugging and optimizing Java Streams. While streams make our code concise and expressive, they can sometimes lead to performance bottlenecks or debugging challenges. In this blog, we’ll learn how to debug stream pipelines, identify common pitfalls, and apply best practices for optimizing stream performance.</p><h3><strong>Debugging Java Streams</strong></h3><p>Streams are inherently declarative, making them challenging to debug compared to traditional loops. Here are some practical techniques to debug stream pipelines effectively:</p><h4>1. Using peek for Debugging</h4><p>The peek method allows you to inspect each element in the pipeline without altering the stream.<br><strong>Example</strong>:</p><pre>import java.util.List;<br><br>public class DebugWithPeek {<br>    public static void main(String[] args) {<br>        List&lt;String&gt; names = List.of(&quot;Alice&quot;, &quot;Bob&quot;, &quot;Charlie&quot;, &quot;David&quot;);<br>        names.stream()<br>            .filter(name -&gt; name.startsWith(&quot;A&quot;))<br>            .peek(name -&gt; System.out.println(&quot;Filtered: &quot; + name))<br>            .map(String::toUpperCase)<br>            .peek(name -&gt; System.out.println(&quot;Mapped: &quot; + name))<br>            .forEach(System.out::println);<br>    }<br>}</pre><p><strong>Output:</strong></p><pre>Filtered: Alice<br>Mapped: ALICE<br>ALICE</pre><h4>2. Breaking Down Pipelines</h4><p>Instead of chaining multiple operations, break down the pipeline into smaller parts for better visibility.<br><strong>Example</strong>:</p><pre>List&lt;String&gt; names = List.of(&quot;Alice&quot;, &quot;Bob&quot;, &quot;Charlie&quot;, &quot;David&quot;);<br>Stream&lt;String&gt; filtered = names.stream().filter(name -&gt; name.startsWith(&quot;A&quot;));<br>Stream&lt;String&gt; mapped = filtered.map(String::toUpperCase);<br>mapped.forEach(System.out::println);</pre><h4>3. Logging Intermediate Results</h4><p>Integrate logging into your stream operations to monitor the flow of data.<br><strong>Example</strong>:</p><pre>import java.util.List;<br>import java.util.logging.Logger;<br><br>public class DebugWithLogging {<br>    private static final Logger LOGGER = Logger.getLogger(DebugWithLogging.class.getName());<br><br>    public static void main(String[] args) {<br>        List&lt;String&gt; names = List.of(&quot;Alice&quot;, &quot;Bob&quot;, &quot;Charlie&quot;, &quot;David&quot;);<br>        names.stream()<br>            .filter(name -&gt; {<br>                boolean startsWithA = name.startsWith(&quot;A&quot;);<br>                LOGGER.info(&quot;Filtered &quot; + name + &quot;: &quot; + startsWithA);<br>                return startsWithA;<br>            })<br>            .map(name -&gt; {<br>                String upper = name.toUpperCase();<br>                LOGGER.info(&quot;Mapped &quot; + name + &quot; to &quot; + upper);<br>                return upper;<br>            })<br>            .forEach(System.out::println);<br>    }<br>}</pre><h3><strong>Optimizing Java Streams</strong></h3><p>Streams are powerful but can lead to inefficiencies if not used correctly. Let’s explore optimization techniques to ensure your stream pipelines are performant.</p><h4>1. Use Parallel Streams Wisely</h4><p>Parallel streams can speed up computation for large datasets by leveraging multiple CPU cores. However, they can add overhead for small datasets or I/O-bound tasks.<br><strong>Example</strong>:</p><pre>import java.util.stream.IntStream;<br><br>public class ParallelStreamExample {<br>    public static void main(String[] args) {<br>        IntStream.range(1, 1000)<br>            .parallel()<br>            .filter(n -&gt; n % 2 == 0)<br>            .forEach(System.out::println);<br>    }<br>}</pre><p><strong>Best Practices:</strong></p><ul><li>Use parallel streams for CPU-intensive tasks.</li><li>Avoid parallel streams for small datasets or when thread synchronization is required.</li></ul><h4>2. Minimize Intermediate Operations</h4><p>Excessive intermediate operations can degrade performance. Combine operations where possible.<br><strong>Example</strong>:</p><pre>// Inefficient<br>numbers.stream().filter(n -&gt; n &gt; 5).map(n -&gt; n * 2).filter(n -&gt; n &lt; 20).collect(Collectors.toList());<br><br>// Optimized<br>numbers.stream().filter(n -&gt; n &gt; 5 &amp;&amp; n * 2 &lt; 20).map(n -&gt; n * 2).collect(Collectors.toList());</pre><h4>3. Avoid Statefulness in Intermediate Operations</h4><p>Stateful operations (e.g., sorted, distinct) require the entire stream to be processed before producing a result. This can lead to memory overhead.<br><strong>Example</strong>:</p><pre>import java.util.List;<br><br>public class StatefulOperation {<br>    public static void main(String[] args) {<br>        List&lt;Integer&gt; numbers = List.of(5, 1, 3, 4, 2);<br>        numbers.stream()<br>            .sorted() // Stateful operation<br>            .forEach(System.out::println);<br>    }<br>}</pre><p><strong>Optimization Tip:</strong> Limit the use of stateful operations, especially on large datasets.</p><h4>4. Use Primitive Streams for Numerical Data</h4><p>Java provides specialized streams (IntStream, LongStream, DoubleStream) for numerical data, which avoids boxing and unboxing overhead.<br><strong>Example</strong>:</p><pre>import java.util.stream.IntStream;<br><br>public class PrimitiveStreams {<br>    public static void main(String[] args) {<br>        int sum = IntStream.range(1, 10)<br>            .sum();<br>        System.out.println(&quot;Sum: &quot; + sum); // Output: Sum: 45<br>    }<br>}</pre><h4>5. Terminate Pipelines Early</h4><p>Use short-circuiting operations like limit and findFirst to terminate pipelines as soon as possible.<br><strong>Example</strong>:</p><pre>import java.util.List;<br><br>public class ShortCircuiting {<br>    public static void main(String[] args) {<br>        List&lt;Integer&gt; numbers = List.of(1, 2, 3, 4, 5);<br>        numbers.stream()<br>            .filter(n -&gt; n % 2 == 0)<br>            .findFirst()<br>            .ifPresent(System.out::println); // Output: 2<br>    }<br>}</pre><h3><strong>Common Pitfalls to Avoid</strong></h3><ul><li><strong>Reusing Streams:</strong> Streams cannot be reused once consumed. Always create a new stream if needed.</li></ul><pre>Stream&lt;String&gt; stream = List.of(&quot;Alice&quot;, &quot;Bob&quot;).stream(); <br>stream.forEach(System.out::println); <br>stream.forEach(System.out::println); // Throws IllegalStateException</pre><ul><li><strong>Overusing Parallel Streams:</strong> Not all tasks benefit from parallelism. Assess the workload before deciding.</li><li><strong>Neglecting Lazy Evaluation:</strong> Remember that intermediate operations are not executed until a terminal operation is called.</li></ul><h3><strong>Key Takeaways</strong></h3><ol><li>Debugging streams requires the creative use of methods like peek and logging.</li><li>Optimizing stream pipelines can significantly improve performance for large datasets.</li><li>Avoid pitfalls like reusing streams and overloading pipelines with unnecessary operations.</li></ol><p><strong>Conclusion</strong><br>Debugging and optimizing Java Streams are essential skills for writing efficient and maintainable code. By leveraging techniques like peek for debugging and adopting best practices for optimization, you can unlock the full potential of streams. This concludes our exploration of Java Streams. If you’ve enjoyed this series, share it with your peers and leave your feedback in the comments below!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d1060bb6637c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part3: Mastering Terminal Operations and Real-World Use Cases with Java Streams]]></title>
            <link>https://medium.com/@codesprintpro/part3-mastering-terminal-operations-and-real-world-use-cases-with-java-streams-4a2a260a71b6?source=rss-295538043760------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a2a260a71b6</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Sachin Sarawgi]]></dc:creator>
            <pubDate>Tue, 14 Jan 2025 14:40:54 GMT</pubDate>
            <atom:updated>2025-01-14T14:40:54.297Z</atom:updated>
            <content:encoded><![CDATA[<p>Welcome to Part 3 of our series on Java Streams! By now, you’ve learned how to create streams (Part 1) and use intermediate operations like filter, map, and flatMap (Part 2). This installment focuses on <strong>terminal operations</strong>, which are the endpoint of every stream pipeline. We’ll also explore real-world use cases to demonstrate how these operations can simplify complex tasks. Whether you’re a student or a working professional, this blog will deepen your understanding of Java Streams.</p><h3><strong>What Are Terminal Operations?</strong></h3><p>Terminal operations mark the end of a stream pipeline. They trigger the execution of all preceding intermediate operations and produce a result, such as a collection, a value, or a side effect. The stream is considered consumed once a terminal operation is invoked and cannot be reused.</p><h4>Types of Terminal Operations</h4><ul><li><strong>Reduction Operations:</strong> Aggregate elements into a single result (e.g., reduce, count).</li><li><strong>Collection Operations:</strong> Gather elements into a collection (e.g., collect).</li><li><strong>Iteration Operations:</strong> Perform an action for each element (e.g., forEach).</li></ul><h3>1. Reduction Operations</h3><p>Reduction operations combine stream elements into a single value using an associative accumulation function.</p><p><strong>Counting Elements with </strong><strong>count<br></strong>The count operation returns the number of elements in a stream.<br>Example:</p><pre>import java.util.List;<br><br>public class CountExample {<br>    public static void main(String[] args) {<br>        List&lt;String&gt; names = List.of(&quot;Alice&quot;, &quot;Bob&quot;, &quot;Charlie&quot;, &quot;David&quot;);<br>        long count = names.stream().count();<br>        System.out.println(&quot;Number of names: &quot; + count); // Output: Number of names: 4<br>    }<br>}</pre><p><strong>Reducing Elements with </strong><strong>reduce<br></strong>The reduce operation aggregates elements into a single result. It takes an initial value and a binary operator.<br>Example:</p><pre>import java.util.List;<br><br>public class ReduceExample {<br>    public static void main(String[] args) {<br>        List&lt;Integer&gt; numbers = List.of(1, 2, 3, 4, 5);<br>        int sum = numbers.stream()<br>            .reduce(0, Integer::sum);<br>        System.out.println(&quot;Sum: &quot; + sum); // Output: Sum: 15<br>    }<br>}</pre><h3>2. Collection Operations</h3><p>The collect operation gathers stream elements into a collection, such as a List, Set, or Map.</p><p><strong>Collecting Data into a List<br></strong>Example:</p><pre>import java.util.List;<br>import java.util.stream.Collectors;<br><br>public class CollectExample {<br>    public static void main(String[] args) {<br>        List&lt;String&gt; names = List.of(&quot;Alice&quot;, &quot;Bob&quot;, &quot;Charlie&quot;);<br>        List&lt;String&gt; filteredNames = names.stream()<br>            .filter(name -&gt; name.startsWith(&quot;C&quot;))<br>            .collect(Collectors.toList());<br><br>        System.out.println(filteredNames); // Output: [Charlie]<br>    }<br>}</pre><p><strong>Grouping Data with </strong><strong>groupingBy<br></strong>The groupingBy collector groups elements based on a classification function.<br>Example:</p><pre>import java.util.List;<br>import java.util.Map;<br>import java.util.stream.Collectors;<br><br>public class GroupingByExample {<br>    public static void main(String[] args) {<br>        List&lt;String&gt; names = List.of(&quot;Alice&quot;, &quot;Anna&quot;, &quot;Bob&quot;, &quot;Charlie&quot;, &quot;David&quot;);<br>        Map&lt;Character, List&lt;String&gt;&gt; groupedByFirstLetter = names.stream()<br>            .collect(Collectors.groupingBy(name -&gt; name.charAt(0)));<br><br>        System.out.println(groupedByFirstLetter);<br>        // Output: {A=[Alice, Anna], B=[Bob], C=[Charlie], D=[David]}<br>    }<br>}</pre><h3>3. Iteration Operations</h3><p>Iteration operations perform an action for each element in the stream.</p><p><strong>Performing Actions with </strong><strong>forEach<br></strong>The forEach operation is commonly used for side effects, such as printing elements.<br>Example:</p><pre>import java.util.List;<br><br>public class ForEachExample {<br>    public static void main(String[] args) {<br>        List&lt;Integer&gt; numbers = List.of(1, 2, 3, 4, 5);<br>        numbers.stream()<br>            .forEach(System.out::println); // Output: 1, 2, 3, 4, 5<br>    }<br>}</pre><h3>Real-World Use Cases</h3><h4>Use Case 1: Processing Employee Data</h4><p>Imagine you have a list of employees, and you need to group them by department and calculate the average salary in each department.<br>Example</p><pre>import java.util.List;<br>import java.util.Map;<br>import java.util.stream.Collectors;<br><br>public class EmployeeProcessing {<br>    static class Employee {<br>        String name;<br>        String department;<br>        double salary;<br><br>        Employee(String name, String department, double salary) {<br>            this.name = name;<br>            this.department = department;<br>            this.salary = salary;<br>        }<br>    }<br><br>    public static void main(String[] args) {<br>        List&lt;Employee&gt; employees = List.of(<br>            new Employee(&quot;Alice&quot;, &quot;HR&quot;, 50000),<br>            new Employee(&quot;Bob&quot;, &quot;IT&quot;, 60000),<br>            new Employee(&quot;Charlie&quot;, &quot;IT&quot;, 70000),<br>            new Employee(&quot;David&quot;, &quot;HR&quot;, 55000)<br>        );<br><br>        Map&lt;String, Double&gt; averageSalaries = employees.stream()<br>            .collect(Collectors.groupingBy(<br>                emp -&gt; emp.department,<br>                Collectors.averagingDouble(emp -&gt; emp.salary)<br>            ));<br><br>        System.out.println(averageSalaries);<br>        // Output: {HR=52500.0, IT=65000.0}<br>    }<br>}</pre><h4>Use Case 2: Analyzing Student Grades</h4><p>You have a list of students with their scores and want to find the highest scorer in each subject.<br>Example</p><pre>import java.util.List;<br>import java.util.Map;<br>import java.util.Comparator;<br>import java.util.stream.Collectors;<br><br>public class StudentAnalysis {<br>    static class Student {<br>        String name;<br>        String subject;<br>        int score;<br><br>        Student(String name, String subject, int score) {<br>            this.name = name;<br>            this.subject = subject;<br>            this.score = score;<br>        }<br>    }<br><br>    public static void main(String[] args) {<br>        List&lt;Student&gt; students = List.of(<br>            new Student(&quot;Alice&quot;, &quot;Math&quot;, 85),<br>            new Student(&quot;Bob&quot;, &quot;Math&quot;, 90),<br>            new Student(&quot;Charlie&quot;, &quot;Science&quot;, 88),<br>            new Student(&quot;David&quot;, &quot;Science&quot;, 92)<br>        );<br><br>        Map&lt;String, Student&gt; topScorers = students.stream()<br>            .collect(Collectors.groupingBy(<br>                student -&gt; student.subject,<br>                Collectors.collectingAndThen(<br>                    Collectors.maxBy(Comparator.comparingInt(student -&gt; student.score)),<br>                    opt -&gt; opt.orElse(null)<br>                )<br>            ));<br><br>        System.out.println(topScorers);<br>        // Output: {Math=Student{name=&#39;Bob&#39;, ...}, Science=Student{name=&#39;David&#39;, ...}}<br>    }<br>}</pre><p><strong>Key Takeaways:</strong></p><ol><li>Terminal operations like reduce, collect, and forEach are essential for concluding stream pipelines.</li><li>Real-world scenarios often combine multiple intermediate and terminal operations for complex data processing.</li><li>Java Streams simplify otherwise tedious tasks, making code more concise and readable.</li></ol><p><strong>Conclusion</strong><br>Terminal operations are where the real power of Java Streams comes into play. By combining them with intermediate operations, you can build pipelines to solve complex problems with minimal effort. In this part, we explored how to use terminal operations like reduce, collect, and forEach, and applied them to real-world scenarios. Stay tuned for the final part of this series, where we’ll cover debugging streams and optimizing performance.</p><p>If you enjoyed this blog, share it with your peers and let us know your thoughts in the comments!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a2a260a71b6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 2: Intermediate Stream Operations]]></title>
            <link>https://medium.com/@codesprintpro/part-2-intermediate-stream-operations-92b25570d76d?source=rss-295538043760------2</link>
            <guid isPermaLink="false">https://medium.com/p/92b25570d76d</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Sachin Sarawgi]]></dc:creator>
            <pubDate>Sat, 11 Jan 2025 05:40:40 GMT</pubDate>
            <atom:updated>2025-01-11T05:40:40.928Z</atom:updated>
            <content:encoded><![CDATA[<p>Welcome to the second part of our series on Java Streams! In Part 1, we introduced the basics of streams and covered their creation and fundamental operations. In this installment, we’ll delve into intermediate operations — the backbone of stream pipelines — and learn how they help transform and manipulate data efficiently. By the end of this blog, you’ll be equipped to create more complex and functional pipelines using Java Streams.</p><h3><strong>What Are Intermediate Operations?</strong></h3><p>Intermediate operations in Java Streams transform or filter data and return a new stream. These operations are lazy, meaning they don’t perform any computation until a terminal operation (e.g., forEach, collect) is invoked. This laziness allows streams to optimize performance by avoiding unnecessary computations.</p><p>Common intermediate operations include:</p><ul><li>filter</li><li>map</li><li>flatMap</li><li>sorted</li><li>distinct</li><li>limit</li><li>skip</li></ul><h3>1. Filtering Data with filter</h3><p>The filter operation is used to include only elements that satisfy a given predicate. It’s commonly used to remove unwanted elements from a stream.<br>Example</p><pre>import java.util.List;<br><br>public class FilterExample {<br>    public static void main(String[] args) {<br>        List&lt;String&gt; names = List.of(&quot;Alice&quot;, &quot;Bob&quot;, &quot;Charlie&quot;, &quot;David&quot;);<br>        names.stream()<br>            .filter(name -&gt; name.startsWith(&quot;A&quot;))<br>            .forEach(System.out::println); // Output: Alice<br>    }<br>}Use Case: Filter employees based on their department, students by grade, or products by category.</pre><p><strong>Use Case:</strong> Filter employees based on their department, students by grade, or products by category.</p><h3>2. Transforming Data with map</h3><p>The map operation applies a transformation function to each element in the stream. It’s useful when you need to convert or process data.<br>Example</p><pre>import java.util.List;<br><br>public class MapExample {<br>    public static void main(String[] args) {<br>        List&lt;String&gt; words = List.of(&quot;java&quot;, &quot;streams&quot;, &quot;are&quot;, &quot;cool&quot;);<br>        words.stream()<br>            .map(String::toUpperCase)<br>            .forEach(System.out::println); // Output: JAVA, STREAMS, ARE, COOL<br>    }<br>}</pre><p><strong>Use Case:</strong> Convert strings to uppercase, calculate square roots, or extract specific fields from objects.</p><h3>3. Flattening Data with flatMap</h3><p>The flatMap operation is used to transform each element into a stream and then flatten all the resulting streams into a single stream. It’s particularly useful when dealing with nested data structures.<br>Example</p><pre>import java.util.List;<br><br>public class FlatMapExample {<br>    public static void main(String[] args) {<br>        List&lt;List&lt;String&gt;&gt; nestedList = List.of(<br>            List.of(&quot;a&quot;, &quot;b&quot;),<br>            List.of(&quot;c&quot;, &quot;d&quot;),<br>            List.of(&quot;e&quot;)<br>        );<br><br>        nestedList.stream()<br>            .flatMap(List::stream)<br>            .forEach(System.out::println); // Output: a, b, c, d, e<br>    }<br>}</pre><p><strong>Use Case:</strong> Flatten lists of lists, tokenize sentences into words, or merge collections of collections.</p><h3>4. Sorting Data with sorted</h3><p>The sorted operation sorts elements in natural order or using a custom comparator.<br>Example:</p><pre>import java.util.List;<br>//Natiral Sorting<br>public class SortedExample {<br>    public static void main(String[] args) {<br>        List&lt;Integer&gt; numbers = List.of(5, 2, 9, 1, 4);<br>        numbers.stream()<br>            .sorted()<br>            .forEach(System.out::println); // Output: 1, 2, 4, 5, 9<br>    }<br>}<br><br><br>import java.util.List;<br>//Custom Sorting<br>public class CustomSortExample {<br>    public static void main(String[] args) {<br>        List&lt;String&gt; names = List.of(&quot;Alice&quot;, &quot;Bob&quot;, &quot;Charlie&quot;);<br>        names.stream()<br>            .sorted((a, b) -&gt; b.compareTo(a)) // Reverse alphabetical order<br>            .forEach(System.out::println); // Output: Charlie, Bob, Alice<br>    }<br>}</pre><p><strong>Use Case:</strong> Sort products by price, employees by age, or strings alphabetically.</p><h3>5. Removing Duplicates with distinct</h3><p>The distinct operation removes duplicate elements from a stream.<br>Example</p><pre>import java.util.List;<br><br>public class DistinctExample {<br>    public static void main(String[] args) {<br>        List&lt;Integer&gt; numbers = List.of(1, 2, 2, 3, 4, 4, 5);<br>        numbers.stream()<br>            .distinct()<br>            .forEach(System.out::println); // Output: 1, 2, 3, 4, 5<br>    }<br>}</pre><p><strong>Use Case:</strong> Eliminate duplicate values from lists or remove redundant data from datasets.</p><h3>6. Limiting and Skipping Elements</h3><ul><li><strong>limit(n):</strong> Truncate the stream to the first n elements.</li><li><strong>skip(n):</strong> Skip the first n elements of the stream.</li></ul><p>Example</p><pre>import java.util.List;<br><br>public class LimitSkipExample {<br>    public static void main(String[] args) {<br>        List&lt;Integer&gt; numbers = List.of(1, 2, 3, 4, 5, 6, 7, 8, 9);<br><br>        // Limit to first 5 elements<br>        numbers.stream()<br>            .limit(5)<br>            .forEach(System.out::println); // Output: 1, 2, 3, 4, 5<br><br>        // Skip the first 5 elements<br>        numbers.stream()<br>            .skip(5)<br>            .forEach(System.out::println); // Output: 6, 7, 8, 9<br>    }<br>}</pre><p><strong>Use Case:</strong> Paginate data or restrict results in processing pipelines.</p><p><strong>Combining Intermediate Operations</strong></p><p>You can combine multiple intermediate operations to create a processing pipeline. For example:</p><pre>import java.util.List;<br>import java.util.stream.Collectors;<br><br>public class CombinedExample {<br>    public static void main(String[] args) {<br>        List&lt;String&gt; names = List.of(&quot;Alice&quot;, &quot;Bob&quot;, &quot;Charlie&quot;, &quot;David&quot;, &quot;Eve&quot;);<br><br>        List&lt;String&gt; result = names.stream()<br>            .filter(name -&gt; name.length() &gt; 3) // Names longer than 3 characters<br>            .map(String::toUpperCase)         // Convert to uppercase<br>            .sorted()                         // Sort alphabetically<br>            .collect(Collectors.toList());    // Collect as a list<br><br>        System.out.println(result); // Output: [ALICE, CHARLIE, DAVID]<br>    }<br>}</pre><p><strong>Important Notes:</strong></p><ol><li>Intermediate operations are lazy and do not execute until a terminal operation is called.</li><li>The order of operations matters; reordering can change the outcome or performance.</li><li>Be mindful of performance when combining multiple operations on large datasets.</li></ol><p><strong>Conclusion</strong><br>Intermediate operations are at the heart of Java Streams, enabling powerful data transformations and filtering. By mastering these operations, you can create efficient and readable pipelines that simplify complex data processing tasks. In the next part, we’ll explore terminal operations and advanced use cases for streams.</p><p>Stay tuned for Part 3, where we dive into terminal operations and explore real-world scenarios. If you enjoyed this blog, share it with your peers and leave your feedback in the comments!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=92b25570d76d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lessons from the Atlassian Outage: Understanding Load Balancers and Blue-Green Deployment]]></title>
            <link>https://medium.com/@codesprintpro/lessons-from-the-atlassian-outage-understanding-load-balancers-and-blue-green-deployment-4fb2778eab0e?source=rss-295538043760------2</link>
            <guid isPermaLink="false">https://medium.com/p/4fb2778eab0e</guid>
            <category><![CDATA[load-balancing]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Sachin Sarawgi]]></dc:creator>
            <pubDate>Fri, 10 Jan 2025 07:09:06 GMT</pubDate>
            <atom:updated>2025-01-10T07:09:06.496Z</atom:updated>
            <content:encoded><![CDATA[<p>In 2019, Atlassian experienced a significant service outage caused by issues with its load balancers. This incident underscored the challenges of managing traffic surges and highlighted the importance of understanding system architecture, resource management, and deployment strategies. In this blog, we’ll break down what happened, why it occurred, and how strategies like load balancer pre-warming and blue-green deployment can help prevent such disruptions. By the end, even a college fresher will have a clear understanding of these concepts.</p><h3><strong>What Happened During the Atlassian Outage?</strong></h3><p>Atlassian’s architecture relied on a typical three-tier system consisting of:</p><ol><li><strong>Load Balancers</strong> — Manage incoming user requests and distribute them across servers.</li><li><strong>API Servers</strong> — Handle business logic and communicate with databases.</li><li><strong>Databases</strong> — Store and retrieve application data.</li></ol><p>The system used AWS’s Elastic Load Balancer (ELB) to handle traffic. However, during the outage:</p><ul><li>Service metrics showed that API servers were functioning well.</li><li>Despite healthy metrics, the load balancer registered zero requests, causing confusion.</li></ul><p>The root cause was linked to newly created servers encountering <strong>out-of-memory (OOM)</strong> errors. Although designed to scale under increasing load, the load balancer failed to handle the traffic effectively due to delayed scaling and resource management issues. This led to a temporary dip in requests.</p><h3><strong>Why Did the Load Balancer Fail?</strong></h3><p>Load balancers are responsible for managing traffic efficiently by distributing requests to multiple servers. However, they have limitations:</p><ol><li><strong>Scaling Delays:</strong><br>Adding new servers to a load balancer takes time — typically between 1 to 7 minutes — before they become fully operational. During this period, the system’s capacity to handle traffic may temporarily degrade.</li><li><strong>Sudden Traffic Spikes:</strong><br>Unpredictable surges in traffic, such as during marketing events or live cricket matches, can overwhelm the load balancer if it’s not prepared.</li><li><strong>Out-of-Memory Errors:</strong><br>New servers may encounter OOM errors due to insufficient resources, preventing them from handling requests effectively.</li></ol><p>These factors combined during the outage, causing the load balancer to falter temporarily.</p><h3><strong>How to Pre-Warn Load Balancers?</strong></h3><p>To avoid such incidents, it’s crucial to prepare load balancers for high traffic scenarios. This process is often referred to as “pre-warming.”</p><h3>What Is Load Balancer Pre-Warming?</h3><p>Pre-warming ensures that a load balancer is ready to handle a sudden influx of traffic by pre-scaling its capacity. Here’s how you can achieve it:</p><ol><li><strong>Consult Cloud Providers:</strong><br>Many cloud service providers, like AWS, offer options to pre-warm load balancers. Reach out to them to understand the requirements for your anticipated traffic.</li><li><strong>Keep Load Balancers ‘Warm’:</strong><br>Regularly send a small amount of traffic to keep the load balancer operational and avoid cold starts.</li><li><strong>Traffic Simulations:</strong><br>Conduct load tests to simulate high-traffic scenarios and verify the system’s performance under stress.</li></ol><h3>Why Is Pre-Warming Important?</h3><p>Without pre-warming, load balancers may take too long to scale, leading to downtime during peak traffic. Pre-warming ensures a smoother handling of traffic surges, reducing the risk of service interruptions.</p><p><strong>What Is Blue-Green Deployment?</strong></p><p>Atlassian also utilized a <strong>blue-green deployment strategy</strong> to manage updates. This approach minimizes downtime and ensures seamless transitions during deployments.</p><h3>Understanding Blue-Green Deployment</h3><p>Blue-green deployment involves maintaining two environments:</p><ol><li><strong>Blue Environment:</strong> The current live environment serving user traffic.</li><li><strong>Green Environment:</strong> The updated environment, ready to replace the blue environment.</li></ol><p>When a deployment is ready:</p><ul><li>Traffic is switched from the blue environment to the green environment.</li><li>The blue environment remains as a fallback in case issues arise.</li></ul><h3>Benefits of Blue-Green Deployment</h3><ol><li><strong>Minimal Downtime:</strong> Users experience little to no disruption during updates.</li><li><strong>Easy Rollbacks:</strong> If the green environment fails, traffic can quickly revert to the blue environment.</li><li><strong>Testing in Production:</strong> The green environment can be tested with real traffic before fully going live.</li></ol><h3>Challenges and Alternatives</h3><p>While blue-green deployment is effective, it may lead to issues if the new environment isn’t sufficiently scaled. Atlassian addressed this by adopting a <strong>rolling deployment</strong> strategy, replacing servers gradually while keeping the same load balancer. This approach resolved their scaling issue permanently.</p><p><strong>Key Takeaways</strong></p><ol><li><strong>Load Balancers Are Not Infinitely Scalable:</strong><br>Proper planning is essential to handle sudden traffic spikes effectively. Understanding their warm-up times and scaling dynamics is crucial.</li><li><strong>Pre-Warming Prevents Cold Starts:</strong><br>Keeping load balancers ready to handle traffic ensures better performance during high-demand events.</li><li><strong>Deployment Strategies Matter:</strong><br>Blue-green deployment minimizes downtime but requires careful preparation. Rolling deployments offer a gradual transition, reducing the risk of performance drops.</li><li><strong>Monitoring and Resource Management:</strong><br>Always monitor infrastructure readiness and ensure new servers have adequate resources to handle traffic.</li></ol><p><strong>Conclusion</strong> The Atlassian outage serves as a valuable lesson in understanding the limitations of load balancers and the importance of proactive traffic management. By adopting strategies like load balancer pre-warming and blue-green deployments, organizations can significantly improve system reliability and scalability.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4fb2778eab0e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part1: Getting Started with Java Streams]]></title>
            <link>https://medium.com/@codesprintpro/getting-started-with-java-streams-fcd204e2fe0d?source=rss-295538043760------2</link>
            <guid isPermaLink="false">https://medium.com/p/fcd204e2fe0d</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Sachin Sarawgi]]></dc:creator>
            <pubDate>Fri, 10 Jan 2025 04:28:55 GMT</pubDate>
            <atom:updated>2025-01-11T05:29:32.860Z</atom:updated>
            <content:encoded><![CDATA[<p>Introduced in Java 8, Java Streams have transformed the way developers process and manipulate data. Streams provide a functional programming paradigm, allowing concise, readable, and efficient operations on data. This first part of the Java Streams series will cover the basics: understanding what streams are, their features, and how to create and use them.</p><h3><strong>What Are Java Streams?</strong></h3><p>Streams in Java are sequences of data elements that support functional-style operations. They allow you to process data declaratively, focusing on “what” you want to achieve rather than “how” to achieve it. Unlike traditional loops, streams abstract away iteration and let you focus on data transformations.</p><p><strong>Key Features:</strong></p><ul><li><strong>Declarative Programming:</strong> Write clean and concise code by describing operations.</li><li><strong>Lazy Evaluation:</strong> Intermediate operations are only executed when a terminal operation is invoked, improving efficiency.</li><li><strong>Pipelining:</strong> Combine multiple operations into a seamless pipeline.</li><li><strong>Parallelism:</strong> Easily process data concurrently.</li></ul><h3><strong>Creating Streams</strong></h3><p>Java Streams can be created from various data sources, including collections, arrays, and generators.</p><p><strong>1. Streams from Collections</strong></p><p>You can create a stream from any collection using the .stream() method.</p><pre>import java.util.List;<br>import java.util.stream.Stream;<br><br>public class StreamFromCollections {<br>    public static void main(String[] args) {<br>        List&lt;String&gt; names = List.of(&quot;Alice&quot;, &quot;Bob&quot;, &quot;Charlie&quot;);<br>        Stream&lt;String&gt; nameStream = names.stream();<br><br>        // Print each name<br>        nameStream.forEach(System.out::println);<br>    }<br>}</pre><p><strong>2. Streams from Arrays</strong></p><p>You can create a stream from an array using Stream.of() or Arrays.stream().</p><pre>import java.util.stream.Stream;<br><br>public class StreamFromArray {<br>    public static void main(String[] args) {<br>        String[] cities = {&quot;New York&quot;, &quot;London&quot;, &quot;Paris&quot;};<br>        Stream&lt;String&gt; cityStream = Stream.of(cities);<br><br>        // Print each city<br>        cityStream.forEach(System.out::println);<br>    }<br>}</pre><p><strong>3. Infinite Streams</strong></p><p>Java Streams support infinite streams using Stream.iterate() and Stream.generate(). These are useful for creating streams with a dynamic size.</p><pre>import java.util.stream.Stream;<br><br>public class InfiniteStreams {<br>    public static void main(String[] args) {<br>        // Generate an infinite stream of integers starting from 1<br>        Stream&lt;Integer&gt; infiniteStream = Stream.iterate(1, n -&gt; n + 1);<br><br>        // Limit the stream to 5 elements and print them<br>        infiniteStream.limit(5).forEach(System.out::println);<br>    }<br>}</pre><h3><strong>Stream Operations</strong></h3><p>Stream operations are categorized into two types: intermediate and terminal.</p><ul><li><strong>Intermediate Operations:</strong> These transform or filter the data and return a new stream. Examples include filter, map, and sorted.</li><li><strong>Terminal Operations:</strong> These produce a final result or a side effect, triggering the execution of intermediate operations. Examples include collect, forEach, and reduce.</li></ul><h4>Intermediate Operations</h4><p>Filtering Data</p><p>The filter operation allows you to include only the elements that meet a specific condition.</p><pre>import java.util.List;<br><br>public class FilterExample {<br>    public static void main(String[] args) {<br>        List&lt;String&gt; names = List.of(&quot;Alice&quot;, &quot;Bob&quot;, &quot;Charlie&quot;, &quot;David&quot;);<br>        names.stream()<br>            .filter(name -&gt; name.startsWith(&quot;A&quot;))<br>            .forEach(System.out::println); // Output: Alice<br>    }<br>}</pre><h4>Terminal Operations</h4><p>Collecting Data</p><p>The collect operation gathers the elements of a stream into a collection, such as a list or a set.</p><pre>import java.util.List;<br>import java.util.stream.Collectors;<br><br>public class CollectExample {<br>    public static void main(String[] args) {<br>        List&lt;String&gt; names = List.of(&quot;Alice&quot;, &quot;Bob&quot;, &quot;Charlie&quot;);<br>        List&lt;String&gt; filteredNames = names.stream()<br>            .filter(name -&gt; name.startsWith(&quot;C&quot;))<br>            .collect(Collectors.toList());<br><br>        System.out.println(filteredNames); // Output: [Charlie]<br>    }<br>}</pre><p>Iterating with forEach</p><p>The forEach operation performs an action for each element in the stream.</p><pre>import java.util.List;<br><br>public class ForEachExample {<br>    public static void main(String[] args) {<br>        List&lt;Integer&gt; numbers = List.of(1, 2, 3, 4, 5);<br>        numbers.stream()<br>            .forEach(System.out::println);<br>    }<br>}</pre><p><strong>Important Notes:</strong></p><ol><li>Streams are not reusable. The stream is considered consumed once a terminal operation is performed and cannot be reused.</li><li>Streams operate on the data source without modifying it.</li><li>Intermediate operations are lazy and executed only when a terminal operation is invoked.</li><li>Be cautious when using infinite streams — always use a limiting operation like limit to avoid excessive resource usage.</li></ol><p><strong>Conclusion</strong><br>Java Streams are a game-changing feature that simplifies data processing with a functional programming style. In this first part of our series, we explored the basics of streams, including their creation and fundamental operations. With this foundation, you are ready to dive deeper into intermediate and advanced concepts in the upcoming parts of this series.</p><p>Stay tuned for Part 2, where we will explore more advanced stream operations, such as flatMap, sorting, and data aggregation. If you found this article helpful, share it with your peers and let us know your thoughts in the comments!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fcd204e2fe0d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Records in Java: Simplifying Data Classes]]></title>
            <link>https://medium.com/@codesprintpro/mastering-records-in-java-simplifying-data-classes-11bc3b9f3aa7?source=rss-295538043760------2</link>
            <guid isPermaLink="false">https://medium.com/p/11bc3b9f3aa7</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Sachin Sarawgi]]></dc:creator>
            <pubDate>Thu, 09 Jan 2025 10:57:41 GMT</pubDate>
            <atom:updated>2025-01-09T10:57:41.633Z</atom:updated>
            <content:encoded><![CDATA[<p>As developers, we often encounter scenarios where we need to create classes that primarily store data. Traditionally, creating such classes in Java involved writing a lot of boilerplate code: constructors, getters, equals, hashCode, and toString methods. It’s repetitive and tedious. Recognizing this, Java was introduced records in Java 14 (as a preview feature) and made it a permanent feature in Java 16. Records simplify the creation of data-holding classes, making your code cleaner, concise, and easier to maintain. In this blog, we’ll explore what records are, their benefits, and how you can use them effectively in your projects.</p><p><strong>What Are Records?</strong></p><p>Records are a special kind of class in Java designed for immutable data. They are perfect for situations where you need to encapsulate data without the verbosity of traditional Java classes. A record automatically generates the following for you:</p><ul><li>A constructor</li><li>Getters for each field</li><li>equals, hashCode, and toString methods</li></ul><p><strong>Example:</strong> Here’s how you define a record:</p><pre>public record Point(int x, int y) {}</pre><p>This single line eliminates the need for multiple lines of boilerplate code.</p><p>Let’s break it down step by step.</p><p><strong>Step-by-Step Guide to Using Records</strong></p><p><strong>Defining a Record</strong><br>Defining a record is as simple as using the record keyword, followed by the record name and its fields:</p><pre>public record User(String name, int age) {}</pre><p>This creates a class with:<br>&gt; Fields name and ageA <br>&gt; A constructor: User(String name, int age)<br>&gt; Getters: name() and age()<br>&gt; equals, hashCode, and toString implementations.</p><p><strong>Creating Instances</strong><br>Creating an instance of a record is straightforward:</p><pre>User user = new User(&quot;Alice&quot;, 25);<br>System.out.println(user.name()); // Prints: Alice<br>System.out.println(user.age());  // Prints: 25</pre><p><strong>Immutability</strong><br>Fields in a record are inherently final. Once created, their values cannot be changed:</p><pre>// user.name = &quot;Bob&quot;; // Compilation error</pre><p>This immutability makes records thread-safe and ideal for concurrent applications.</p><p><strong>Adding Custom Methods</strong><br>Records can also contain custom methods:</p><pre>public record Product(String name, double price) {<br>    public double applyDiscount(double percentage) {<br>        return price - (price * percentage / 100);<br>    }<br>}</pre><p><strong>Custom Constructors</strong><br>You can validate data or perform operations in the canonical constructor:</p><pre>public record Employee(String name, int salary) {<br>    public Employee {<br>        if (salary &lt; 0) {<br>            throw new IllegalArgumentException(&quot;Salary cannot be negative&quot;);<br>        }<br>    }<br>}</pre><p><strong>Benefits of Using Records</strong></p><ol><li><strong>Reduced Boilerplate:</strong><br>With records, you no longer need to manually write constructors, getters, and utility methods. The result is cleaner and more maintainable code.</li><li><strong>Readable Code:</strong><br>Records communicate that their purpose is to hold data, making your code more understandable.</li><li><strong>Immutability:</strong><br>Records promote immutability by design, ensuring your data remains consistent and safe in multi-threaded environments.</li></ol><p><strong>Limitations and Important Notes:</strong></p><ul><li>Records are immutable. If you need mutable data, records are not the right choice.</li><li>They cannot extend other classes (but they can implement interfaces).</li><li>You cannot explicitly set fields to null unless allowed in the canonical constructor.</li><li>Records are not suitable for all use cases — for instance, classes with complex logic or behavior.</li></ul><p><strong>Code Example:</strong> Here’s a comprehensive example that demonstrates the power of records:</p><pre>import java.util.Objects;<br>public record Employee(String name, String department, double salary) {<br>    public Employee {<br>        // Validate inputs<br>        Objects.requireNonNull(name, &quot;Name cannot be null&quot;);<br>        Objects.requireNonNull(department, &quot;Department cannot be null&quot;);<br>        if (salary &lt; 0) {<br>            throw new IllegalArgumentException(&quot;Salary must be positive&quot;);<br>        }<br>    }<br>    public double annualSalary() {<br>            return salary * 12;<br>        }<br>        public String employeeDetails() {<br>            return String.format(&quot;%s works in %s department and earns %.2f annually.&quot;, name, department, annualSalary());<br>        }<br>    }<br>    public class Main {<br>        public static void main(String[] args) {<br>            Employee emp = new Employee(&quot;John&quot;, &quot;Engineering&quot;, 5000);<br>            System.out.println(emp.employeeDetails());<br>        }<br>    }<br>}</pre><p><strong>When to Use Records:</strong></p><ul><li>When you need a class whose primary purpose is to store data.</li><li>When you want to avoid boilerplate code.</li><li>When immutability and thread safety are critical.</li></ul><p><strong>When Not to Use Records:</strong></p><ul><li>When you need mutable fields.</li><li>When your class requires complex behavior or logic.</li></ul><p><strong>Conclusion</strong><br>Records are a powerful addition to Java’s arsenal, providing a clean and efficient way to define data-holding classes. By reducing boilerplate code and promoting immutability, they help developers write more concise and robust applications. Whether you’re building APIs, working with DTOs, or simply organizing your data, records can make your life easier.</p><p>Try using records in your next project and experience the difference for yourself. Have questions or interesting use cases? Drop them in the comments below — I’d love to hear from you! If you found this post helpful, don’t forget to share it with your fellow developers!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=11bc3b9f3aa7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java’s Z Garbage Collector: Achieving Low Latency at Scale]]></title>
            <link>https://medium.com/@codesprintpro/javas-z-garbage-collector-achieving-low-latency-at-scale-809fb43bf046?source=rss-295538043760------2</link>
            <guid isPermaLink="false">https://medium.com/p/809fb43bf046</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Sachin Sarawgi]]></dc:creator>
            <pubDate>Thu, 09 Jan 2025 06:38:15 GMT</pubDate>
            <atom:updated>2025-01-09T06:38:15.924Z</atom:updated>
            <content:encoded><![CDATA[<h3>If you’ve ever worked on applications requiring high throughput and low latency, you know how challenging managing garbage collection (GC) without introducing noticeable pauses can be. With the introduction of the Z Garbage Collector (ZGC) in Java, managing GC pauses has become significantly easier. ZGC is a low-latency garbage collector that aims to maintain pause times below 10ms, even for heaps as large as 16TB.</h3><p><strong>Why Does Garbage Collection Matter?</strong></p><p>Garbage collection is a critical aspect of Java’s memory management. While it simplifies memory handling for developers, traditional garbage collectors can introduce unpredictable pauses during GC cycles, especially for applications with large heaps or real-time requirements. These pauses can lead to performance bottlenecks and user dissatisfaction in latency-sensitive systems such as trading platforms, gaming servers, or IoT applications.</p><p><strong>What Is ZGC?</strong></p><p>ZGC is a scalable, low-latency garbage collector introduced in Java 11 as an experimental feature and made production-ready in later versions. It was designed with three key goals:</p><ol><li><strong>Low Latency:</strong> Keep pause times consistently under 10ms.</li><li><strong>Scalability:</strong> Handle heaps ranging from kilobytes to terabytes efficiently.</li><li><strong>Simplicity:</strong> Minimize GC tuning, allowing developers to focus on their applications.</li></ol><p><strong>Key Features of ZGC</strong></p><ul><li><strong>Concurrent Execution:</strong> Most of ZGC’s work is performed concurrently with the application threads. This means your application keeps running while garbage collection happens in the background.</li><li><strong>Region-Based Memory Management:</strong> ZGC divides the heap into small regions, making memory management more efficient.</li><li><strong>Colored Pointers:</strong> ZGC uses a unique approach called “colored pointers” to track object references, avoiding the need for stop-the-world pauses during object relocation.</li><li><strong>Huge Heap Support:</strong> ZGC can handle heaps as large as 16TB without performance degradation</li></ul><p><strong>How to Enable ZGC</strong></p><p>Enabling ZGC in your Java application is straightforward. Here are the steps:</p><ol><li><strong>Add JVM Options: </strong>Use the following JVM options to enable ZGC:<br>-XX:+UnlockExperimentalVMOptions -XX:+UseZGC</li><li><strong>Heap Configuration:</strong><br>While ZGC requires minimal tuning, you can set the initial and maximum heap size using -Xms and -Xmx options:<br>-Xms4g -Xmx4g</li><li><strong>Java Version Compatibility:</strong><br>Ensure you’re using Java 11 or later. ZGC has been significantly improved in subsequent Java versions, so it’s recommended to use the latest LTS version.</li></ol><p><strong>Step-by-Step Code Example</strong></p><p>Here’s a simple example to demonstrate ZGC in action:</p><pre>public class ZGCDemo {<br>    public static void main(String[] args) {<br>        System.out.println(&quot;Starting ZGC Demo...&quot;);<br>        for (int i = 0; i &lt; 1_000_000; i++) {<br>            String data = &quot;Example Data &quot; + i;<br>            if (i % 100_000 == 0) {<br>                System.out.println(&quot;Processed: &quot; + i + &quot; items&quot;);<br>            }<br>        }<br>        System.out.println(&quot;ZGC Demo Completed.&quot;);<br>    }<br>}Understanding ZGC’s Colored Pointers</pre><p>Run this program with the ZGC JVM options:</p><pre>java -XX:+UnlockExperimentalVMOptions -XX:+UseZGC -Xms2g -Xmx2g ZGCDemo</pre><p>One of ZGC’s standout features is its use of colored pointers. This technique encodes metadata directly into the pointer, allowing ZGC to track object references without the need for stop-the-world pauses. Colored pointers enable ZGC to:</p><ul><li>Perform concurrent compaction, ensuring heap fragmentation is managed without blocking application threads.</li><li>Accurately track objects, even during relocation.</li></ul><p><strong>How It Works:</strong></p><ul><li>A few bits in the pointer are reserved for metadata, such as whether the object has been marked or relocated.</li><li>The remaining bits are used for the actual memory address.</li></ul><p>This innovative approach minimizes overhead while maintaining high performance.</p><p><strong>Best Practices for Using ZGC</strong></p><ol><li><strong>Use Cases: </strong>ZGC is ideal for applications with low-latency requirements, such as: <br>&gt; Real-time financial systems<br>&gt; Online gaming platforms<br>&gt; Machine learning workloads</li><li><strong>Monitoring Performance:</strong><br>Use tools like Java Flight Recorder (JFR) and JDK Mission Control to monitor ZGC’s performance and understand its impact on your application.</li><li><strong>Avoid Excessive GC Calls:</strong><br>Although ZGC minimizes GC pauses, explicitly calling System.gc() can still disrupt performance. Rely on ZGC’s automatic management instead.</li><li><strong>Heap Sizing:</strong><br>Allocate sufficient heap memory to allow ZGC to work effectively. While ZGC can handle huge heaps, smaller heaps may benefit more from other collectors like G1.</li></ol><p><strong>Important Notes</strong></p><ul><li>ZGC is optimized for large heaps and low latency. For smaller applications, the G1 GC might be a better choice.</li><li>Since ZGC uses concurrent execution, it’s CPU-intensive. Ensure your system has adequate CPU resources.</li><li>ZGC works best with modern hardware and JVM versions. Regularly update your JVM to leverage the latest improvements.</li></ul><p><strong>Conclusion</strong><br>The Z Garbage Collector represents a significant step forward in Java’s GC technology. By enabling low-latency garbage collection with minimal tuning, ZGC empowers developers to build scalable, real-time applications without worrying about GC pauses. Whether you’re working on a trading system, an online game, or any latency-sensitive application, ZGC is a tool worth exploring.</p><p>Try ZGC in your next project and share your experiences in the comments below. Don’t forget to clap if you found this article helpful — it motivates me to create more content like this!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=809fb43bf046" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java 17: What’s New and How It Will Change Your Coding]]></title>
            <link>https://medium.com/codesprintpro/java-17-whats-new-and-how-it-will-change-your-coding-fad53c06a555?source=rss-295538043760------2</link>
            <guid isPermaLink="false">https://medium.com/p/fad53c06a555</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[learning]]></category>
            <dc:creator><![CDATA[Sachin Sarawgi]]></dc:creator>
            <pubDate>Sat, 06 Jul 2024 07:05:10 GMT</pubDate>
            <atom:updated>2024-07-06T07:05:10.031Z</atom:updated>
            <content:encoded><![CDATA[<p>Java 17, the latest Long-Term Support (LTS) release of Java, brings a host of new features, enhancements, and deprecations that promise to improve the developer experience and application performance. As developers, staying updated with these changes is crucial to leverage the full potential of the language and maintain best practices. In this blog, we’ll explore the key features introduced in Java 17, complete with examples and insights on how they can impact your coding.</p><h4>1. Sealed Classes</h4><p>Sealed classes introduce a new way to control class hierarchies. By restricting which classes can be extended or implemented, sealed classes enhance encapsulation and improve code readability.</p><pre>public abstract sealed class Shape permits Circle, Square {}<br><br>public final class Circle extends Shape {<br>    // Implementation<br>}<br><br>public final class Square extends Shape {<br>    // Implementation<br>}</pre><p>In this example, the Shape class can only be extended by Circle and Square. Any attempt to extend it with another class will result in a compilation error.</p><h4>2. Pattern Matching for Switch (Preview)</h4><p>Pattern matching simplifies code by allowing you to extract components from objects more succinctly. Java 17 extends this capability to switch statements.</p><p><strong>Example:</strong></p><pre>public String formatShape(Shape shape) {<br>    return switch (shape) {<br>        case Circle c -&gt; String.format(&quot;Circle with radius %f&quot;, c.radius());<br>        case Square s -&gt; String.format(&quot;Square with side %f&quot;, s.side());<br>        default -&gt; throw new IllegalStateException(&quot;Unexpected value: &quot; + shape);<br>    };<br>}</pre><p>This pattern-matching syntax makes the code more concise and readable.</p><h4>3. Enhanced Pseudo-Random Number Generators</h4><p>Java 17 introduces new interfaces and implementations for random number generation, enhancing flexibility and performance.</p><p><strong>Example:</strong></p><pre>import java.util.random.RandomGenerator;<br>import java.util.random.RandomGeneratorFactory;<br>public class RandomExample {<br>    public static void main(String[] args) {<br>        RandomGenerator generator = RandomGeneratorFactory.of(&quot;L128X256MixRandom&quot;).create();<br>        System.out.println(generator.nextInt());<br>    }<br>}</pre><p>This code demonstrates the use of the new RandomGenerator interface to generate random numbers.</p><h4>4. Deprecations and Removals</h4><p>Java 17 removes and deprecates several outdated features, encouraging developers to use more modern alternatives. Notably, the experimental AOT and JIT compilers have been removed.</p><p><strong>Removed Features:</strong></p><ul><li><strong>Experimental AOT and JIT Compilers</strong>: These compilers were rarely used and their removal simplifies the JDK.</li><li><strong>RMI Activation</strong>: The Remote Method Invocation (RMI) Activation mechanism is removed due to low usage and the availability of more modern alternatives.</li></ul><p><strong>Deprecated Features:</strong></p><ul><li><strong>Applets</strong>: Applets have been deprecated and their support in modern browsers is minimal. Use modern web technologies like HTML5 and JavaScript instead.</li><li><strong>Security Manager</strong>: The Security Manager is deprecated for removal in a future release. Applications should use modern security practices and frameworks.</li></ul><h4>5. Strong Encapsulation in the JDK</h4><p>Encapsulation enhancements restrict access to internal APIs, promoting better security and stability. Modules now require explicit exports for reflective access.</p><p><strong>Example:</strong></p><pre>module my.module {<br>    exports com.example.myapp;<br>}</pre><p>This module declaration explicitly exports the com.example.myapp package, ensuring only intended packages are accessible.</p><h3>How Java 17 Will Change Your Coding</h3><ol><li><strong>Improved Code Quality</strong>: Features like sealed classes and pattern matching for switches enable cleaner, more maintainable code.</li><li><strong>Enhanced Performance</strong>: The new random number generators and other performance enhancements can lead to more efficient applications.</li><li><strong>Better Security</strong>: Strong encapsulation and the removal of deprecated features ensure a more secure codebase.</li><li><strong>Future-Proofing</strong>: Adopting the latest language features prepares your code for future Java versions, reducing technical debt.</li></ol><h3>Conclusion</h3><p>Java 17 brings significant advancements that can transform how you write and maintain your code. By leveraging these new features, you can create more robust, efficient, and secure applications. Stay tuned for more in-depth guides and examples on Java 17 and beyond!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fad53c06a555" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codesprintpro/java-17-whats-new-and-how-it-will-change-your-coding-fad53c06a555">Java 17: What’s New and How It Will Change Your Coding</a> was originally published in <a href="https://medium.com/codesprintpro">White Collar Professional</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Boot with Jasypt 1:1]]></title>
            <link>https://medium.com/javarevisited/spring-boot-with-jasypt-1-1-f8b943d57cb?source=rss-295538043760------2</link>
            <guid isPermaLink="false">https://medium.com/p/f8b943d57cb</guid>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[cryptocurrency]]></category>
            <dc:creator><![CDATA[Sachin Sarawgi]]></dc:creator>
            <pubDate>Mon, 24 Apr 2023 08:52:14 GMT</pubDate>
            <atom:updated>2023-04-24T15:38:16.490Z</atom:updated>
            <content:encoded><![CDATA[<p>Jasypt library offers encryption and decryption for <a href="https://javarevisited.blogspot.com/2021/06/4-examples-of-text-blocks-in-java.html">text strings</a>, passwords, and other private data. In order to protect sensitive data kept in configuration and property files, it can be utilised with Spring Boot. <br>Think of scenarios where you set actual API key for third-party libraries in the AWS parameter store</p><p>This blog will show how you can set up Jasypt with Spring Boot and use encrypted properties.</p><figure><a href="https://javarevisited.blogspot.com/2021/06/4-examples-of-text-blocks-in-java.html"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R8m-4UWhRXCFNGWn6js_Sg.jpeg" /></a></figure><h4>Step1: Setup Spring Project using https://start.spring.io</h4><ul><li>Open your web browser and navigate to the Spring Initializr website at <a href="https://start.spring.io/">https://start.spring.io/.</a></li></ul><p>Fill in the following details:<br>– Project: Maven Project<br>– Language: Java<br>– Spring Boot: 3.0.6<br>– Group: com.learning.springbootwithjasypt<br>– Artifact: springboot-with-jasypt<br>– Packaging: Jar<br>– Java: 17<br>– Description: Demo project for Spring Boot with Jasypt</p><ul><li>Click on Add dependencies and add the following dependencies:<br>– Spring Web</li><li>Click on Generate and download the generated zip file.</li><li>You can import your produced project into your preferred IDE and develop your application once you have it.</li><li>After all configuration, the setup should look like this.</li></ul><figure><a href="https://www.java67.com/2021/02/spring-boot-actuator-interview-questions-answers-java.html"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XgSddTTdAlUsjsxV7ZtQFQ.png" /></a></figure><h4>Step2: Add necessary dependency in pom.xml</h4><ul><li>Unzip the project and open it in your favourite IDE.</li><li>Add the following dependency under dependencies<br>Note: This is needed for performing encryption and decryption of properties. You can find latest version <a href="https://mvnrepository.com/artifact/com.github.ulisesbocchio/jasypt-spring-boot-starter">here</a></li></ul><pre>&lt;dependency&gt;<br>   &lt;groupId&gt;com.github.ulisesbocchio&lt;/groupId&gt;<br>   &lt;artifactId&gt;jasypt-spring-boot-starter&lt;/artifactId&gt;<br>   &lt;version&gt;3.0.5&lt;/version&gt;<br>&lt;/dependency&gt;</pre><ul><li>Add plugin dependency to generate the encrypted password under plugins<br>Note: This depndency is needed to generate encrypted password through command line</li></ul><pre>&lt;plugin&gt;<br>    &lt;groupId&gt;com.github.ulisesbocchio&lt;/groupId&gt;<br>    &lt;artifactId&gt;jasypt-maven-plugin&lt;/artifactId&gt;<br>    &lt;version&gt;3.0.5&lt;/version&gt;<br>&lt;/plugin&gt;</pre><h4>Step3: Generate encrypted properties</h4><ul><li>Got to the application.properties file under the resources folder and add a property</li></ul><pre>database.password=ENC()</pre><ul><li>Inside ENS we have to put the encrypted content. Suppose the password was password 😇</li><li>Go to the command prompt and type the following command<br>Note: Djasypt.encryptor.password is the secret key we are using to encrypt and decrypt the properties. -Djasypt.plugin.value is the actual content we want to encrypt.</li></ul><pre>mvn jasypt:encrypt-value -Djasypt.encryptor.password=jasypt_password -Djasypt.plugin.value=password</pre><ul><li>Now whatever value it’s giving just put the content inside the ENC().</li></ul><pre>database.password=ENC(8j8xGbU2Tx33VigC390w17onLCM9QEqWjKqUnpSZ6SyG2Sydz6Vz/oP70lJiLmD9)</pre><ul><li>Now when you start the application, it needs to know which secret key we used for encryption so that it can decrypt. So don&#39;t forget to add the following VM option while running the application.</li></ul><pre>-Djasypt.encryptor.password=jasypt_password</pre><h4>Step4: Add a controller to access the property</h4><ul><li>Create a <a href="https://medium.com/javarevisited/difference-between-controller-service-and-repository-annotations-in-spring-framework-c2d110e6436a">controller </a>with the following content</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bac63d9b929fdf49be0f91ffc313bd1f/href">https://medium.com/media/bac63d9b929fdf49be0f91ffc313bd1f/href</a></iframe><h4>Step5: Access the encrypted value</h4><ul><li>Start your application by running the main SpringBootApplication class.</li><li>Access the value using GET API <a href="http://localhost:8080/demo">http://localhost:8080/demo</a></li><li>You will get the decrypted value.</li></ul><p>The whole project can be found at this GitHub link <a href="https://github.com/codesprintpro/springbootwithjasypt">https://github.com/codesprintpro/springbootwithjasypt</a>.</p><p>I hope this blog will help in using encrypted values for all the important passwords, and API keys which we use locally or mainly in the cloud environment.</p><p><em>If you enjoyed reading this, don’t forget the applause. 👏<br>Thank you.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f8b943d57cb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/javarevisited/spring-boot-with-jasypt-1-1-f8b943d57cb">Spring Boot with Jasypt 1:1</a> was originally published in <a href="https://medium.com/javarevisited">Javarevisited</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>