<?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 Naveen on Medium]]></title>
        <description><![CDATA[Stories by Naveen on Medium]]></description>
        <link>https://medium.com/@dnrvec?source=rss-3c8a25e4419c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*3MPM4G3NvS04GA9Z.jpg</url>
            <title>Stories by Naveen on Medium</title>
            <link>https://medium.com/@dnrvec?source=rss-3c8a25e4419c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 06:14:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dnrvec/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[Understanding the world of Spring in Java]]></title>
            <link>https://medium.com/@dnrvec/understanding-the-world-of-spring-in-java-aed4fbb081d5?source=rss-3c8a25e4419c------2</link>
            <guid isPermaLink="false">https://medium.com/p/aed4fbb081d5</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-framework]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Naveen]]></dc:creator>
            <pubDate>Mon, 28 Jul 2025 04:04:09 GMT</pubDate>
            <atom:updated>2025-07-28T04:04:09.432Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’re exploring backend Java development, chances are you’ve encountered “Spring,” “Spring Framework,” and “Spring Boot.” These terms can seem confusing, but they build on each other in meaningful ways. Let’s break down their relationship, their major differences, and the most important new features introduced in recent versions.</p><h4>What’s the Difference?</h4><p>Think of Spring as an ecosystem — a collection of open-source tools that help you build robust, maintainable Java applications. Within this ecosystem:</p><ul><li><strong>Spring Framework: </strong>The foundational library. It’s modular and provides core features like dependency injection, transaction support, JDBC, and more.</li><li><strong>Spring Boot:</strong> An extension of Spring Framework that offers a faster, opinionated way to build and launch new applications. It reduces boilerplate and lets you focus on writing business logic — not plumbing.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1jTu6TKTR-uBGTlqG96E3A.png" /></figure><blockquote><strong>Spring Framework</strong></blockquote><p>The core programming and configuration model.</p><p>Major Modules:</p><ul><li>Core Container (IoC/DI)</li><li>Spring MVC (Web)</li><li>Spring AOP</li><li>Spring JDBC / ORM</li><li>Spring Test</li></ul><p><strong>Key Features:</strong></p><ul><li>Inversion of Control (IoC) via @Component, @Autowired</li><li>Declarative transaction management</li><li>RESTful MVC</li><li>Integration with JPA, JDBC, JMS, etc.</li></ul><blockquote><strong>Spring Boot</strong></blockquote><p><strong>Spring Boot</strong> simplifies Spring app development by:</p><p><strong>Key Features:</strong></p><ul><li>Auto-configuration (e.g., auto-sets up Spring MVC, Jackson, Hibernate, etc.)</li><li>Embedded servers (Tomcat/Jetty/Undertow)</li><li>Opinionated defaults to reduce boilerplate</li><li>Spring Boot Starters (spring-boot-starter-web, -data-jpa, etc.)</li><li>Actuator for monitoring</li><li>Spring Boot CLI and dev tools</li></ul><p>🔧 <strong>Without Boot</strong>:</p><pre>@Configuration<br>@EnableWebMvc<br>public class AppConfig {<br>   ...<br>}</pre><pre>@Bean<br>public DataSource dataSource() {<br>    DriverManagerDataSource ds = new DriverManagerDataSource();<br>    ds.setUrl(&quot;jdbc:mysql://localhost:3306/db&quot;);<br>    ds.setUsername(&quot;root&quot;);<br>    ds.setPassword(&quot;password&quot;);<br>    return ds;<br>}<br><br>@Bean<br>public JdbcTemplate jdbcTemplate() {<br>    return new JdbcTemplate(dataSource());<br>}</pre><p>✅ <strong>With Boot</strong>:</p><pre>@SpringBootApplication<br>public class App {<br>    public static void main(String[] args) {<br>        SpringApplication.run(App.class, args);<br>    }<br>}</pre><pre>spring.datasource.url=jdbc:mysql://localhost:3306/db<br>spring.datasource.username=root<br>spring.datasource.password=password</pre><blockquote><strong>Key Features Introduced in Recent Versions</strong></blockquote><p><strong>Spring Framework (latest: 6.2+, 7.0 preview)</strong></p><ul><li>Modern Java: Requires Java 17+, aligning with new language features and performance improvements.</li><li>Jakarta EE Migration: Core packages have shifted from the older Javax namespace to Jakarta EE, reflecting the Java ecosystem’s evolution.</li><li>Native Image Support: Better integration with GraalVM, allowing you to compile Java apps to ultra-fast native binaries.</li><li>Enhanced Reactive Programming: Building scalable, event-driven apps is now easier thanks to improved reactive APIs.</li><li>API Modernization: Full alignment with the latest Jakarta EE APIs, making it future-proof for enterprise development.</li></ul><p><strong>Spring Boot (latest: 3.5.x as of July 2025)</strong></p><ul><li>Native Executables: First-class support for natively compiled images with GraalVM for faster startup, lower memory.</li><li>Observability: Integrated monitoring and tracing (Micrometer, OpenTelemetry), plus out-of-the-box health checks.</li><li>Structured Logging &amp; Diagnostics: Improved logging and diagnostics utilities, including better support for cloud-native deployment.</li><li>Developer Productivity: Tools for generating Docker/OCI images, improved ARM64 support, easier integration with Docker Compose.</li><li>Testing Improvements: Better support for testing Spring MVC apps with new assertion libraries.</li><li>Advanced Configuration: Flexible property loading, improved security defaults, more robust validation of config properties.</li></ul><p><strong>What Should You Choose for Your Next Project?</strong></p><ul><li>Spring Boot is the go-to for most modern Java backend projects. It’s fast to set up, makes cloud deployment a breeze, and comes with production-readiness features.</li><li>Spring Framework (without Boot) is the right choice only if you need full control for highly customized or legacy enterprise systems.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*LFtkxbHGLrsSCnyt7C2B2w.png" /></figure><h4>Final Thoughts</h4><p>Spring has transformed the way Java developers build web applications, shifting from clunky manual configuration to lightning-quick auto-setup and production-ready packaging. Choosing between Spring Framework and Spring Boot isn’t just about technology — it’s about the kind of developer experience and scalability you want for your project.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aed4fbb081d5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Demystifying Maven Build Essentials]]></title>
            <link>https://medium.com/@dnrvec/demystifying-maven-build-essentials-8db5b5d92244?source=rss-3c8a25e4419c------2</link>
            <guid isPermaLink="false">https://medium.com/p/8db5b5d92244</guid>
            <category><![CDATA[maven]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Naveen]]></dc:creator>
            <pubDate>Mon, 28 Jul 2025 02:58:36 GMT</pubDate>
            <atom:updated>2025-07-28T02:58:36.225Z</atom:updated>
            <content:encoded><![CDATA[<p>Building modern Java applications involves more than just writing code — you need to manage dependencies, configure build steps and sometimes even generate server‑ and client‑side code from API contracts.</p><p>This article explores key elements of the Java build ecosystem: the Maven Project Object Model (POM), the local .m2 repository, build lifecycles and dependency scopes. Together they form the backbone of reproducible builds.</p><blockquote><strong>The Maven POM (Project Object Model)</strong></blockquote><p>Maven uses an XML file named pom.xml to describe how a project should be built. The POM is the fundamental unit of work in Maven: when you run a Maven goal, the tool reads the POM, retrieves configuration information and executes the requested phase or plugin. The POM contains default values for common build locations (e.g., src/main/java for sources and target for build output) and defines elements such as:</p><ul><li>Project coordinates — groupId, artifactId and version uniquely identify an artifact. Maven combines them into a fully qualified artifact name in the form groupId:artifactId:version. If packaging is not specified, Maven assumes a JAR.</li><li>Dependencies — Libraries your project needs. You list each dependency with its coordinates and optional scope. Maven handles transitive dependencies (dependencies of dependencies) automatically.</li><li>Plugins — Tasks executed during the build (e.g., compiler, test runners, code generators). Plugins themselves can have configurations and execution goals.</li><li>Build profiles — custom configurations that activate based on environment or command‑line flags.</li></ul><p>A POM may inherit from a parent POM, gaining shared configuration such as dependency versions or plugin settings. This inheritance is defined via a &lt;parent&gt; element, and modules can inherit the groupId and version from the parent by omitting them in the child POM. You can also aggregate multiple modules by setting the parent’s packaging to pom and listing &lt;module&gt; entries.</p><p>At minimum a POM must contain the following elements:</p><pre>&lt;project xmlns=&quot;http://maven.apache.org/POM/4.0.0&quot;&gt;<br>    &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;<br>    &lt;groupId&gt;com.example&lt;/groupId&gt;<br>    &lt;artifactId&gt;my-app&lt;/artifactId&gt;<br>    &lt;version&gt;1.0.0&lt;/version&gt;<br>&lt;/project&gt;</pre><p>Maven will fill in other details (e.g., default packaging, repositories) using the Super POM and conventions. In a multi‑module build, you create a parent POM with pom packaging and list child modules; each module can override or extend inherited settings.</p><p>The <strong>Super POM</strong> is the default POM that all Maven projects inherit implicitly<strong> </strong>if you don’t specify certain elements in your own pom.xml.</p><p>Think of it as the parent-of-all Maven POMs. It provides sensible defaults so you don’t have to define every detail manually.</p><p>It’s defined in Maven’s internal files (maven-model-builder) and applies to every Maven project, unless you override it.</p><p>If you don’t specify a &lt;parent&gt; in your pom.xml, you still get inherited behavior from the Super POM.</p><p>A <strong>Parent POM</strong> is a Maven POM file that is explicitly <strong>inherited</strong> by one or more child projects.</p><p><strong>Example</strong>:- Imagine you have 5 microservices or Java libraries. Rather than repeating the same compiler settings, test framework versions, and repo URLs, you define them in a <strong>Parent POM</strong>, and each service just declares.</p><pre>&lt;parent&gt;<br>    &lt;groupId&gt;com.mycompany&lt;/groupId&gt;<br>    &lt;artifactId&gt;build-standards&lt;/artifactId&gt;<br>    &lt;version&gt;2.3.1&lt;/version&gt;<br>&lt;/parent&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SzgN36RZ0Clcz943m5cNHg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*ZqU-vqsqCctBlLsRyEzNrg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1017/1*wuoVBUSFt2jpGHvAjKMnlQ.png" /></figure><pre>// Example<br><br>&lt;project xmlns=&quot;http://maven.apache.org/POM/4.0.0&quot;<br>         xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;<br>         xsi:schemaLocation=&quot;http://maven.apache.org/POM/4.0.0 <br>                             http://maven.apache.org/xsd/maven-4.0.0.xsd&quot;&gt;<br>    <br>    &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;<br><br>    &lt;groupId&gt;com.example&lt;/groupId&gt;<br>    &lt;artifactId&gt;my-app&lt;/artifactId&gt;<br>    &lt;version&gt;1.0.0&lt;/version&gt;<br>    &lt;packaging&gt;jar&lt;/packaging&gt;<br>    &lt;modules&gt;<br>      &lt;module&gt;module-a&lt;/module&gt;<br>      &lt;module&gt;module-b&lt;/module&gt;<br>    &lt;/modules&gt;<br><br>    &lt;name&gt;My Application&lt;/name&gt;<br>    &lt;description&gt;A simple Maven project example&lt;/description&gt;<br><br>    &lt;dependencies&gt;<br>        &lt;!-- Example dependency: JUnit for testing --&gt;<br>        &lt;dependency&gt;<br>            &lt;groupId&gt;junit&lt;/groupId&gt;<br>            &lt;artifactId&gt;junit&lt;/artifactId&gt;<br>            &lt;version&gt;4.13.2&lt;/version&gt;<br>            &lt;scope&gt;test&lt;/scope&gt;<br>        &lt;/dependency&gt;<br>    &lt;/dependencies&gt;<br><br>    &lt;build&gt;<br>        &lt;plugins&gt;<br>            &lt;!-- Maven Compiler Plugin --&gt;<br>            &lt;plugin&gt;<br>                &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;<br>                &lt;artifactId&gt;maven-compiler-plugin&lt;/artifactId&gt;<br>                &lt;version&gt;3.10.1&lt;/version&gt;<br>                &lt;configuration&gt;<br>                    &lt;source&gt;1.8&lt;/source&gt;<br>                    &lt;target&gt;1.8&lt;/target&gt;<br>                &lt;/configuration&gt;<br>            &lt;/plugin&gt;<br>        &lt;/plugins&gt;<br>    &lt;/build&gt;<br>&lt;/project&gt;</pre><pre>// module-a/pom.xml<br>&lt;project&gt;<br>  &lt;parent&gt;<br>    &lt;groupId&gt;com.example&lt;/groupId&gt;<br>    &lt;artifactId&gt;my-app&lt;/artifactId&gt;<br>    &lt;version&gt;1.0.0&lt;/version&gt;<br>  &lt;/parent&gt;<br>  &lt;artifactId&gt;module-a&lt;/artifactId&gt;<br>&lt;/project&gt;</pre><blockquote><strong>The </strong><strong>.m2 Repository</strong></blockquote><p>When Maven downloads dependencies and plugins, it caches them in a local repository under your home directory (${user.home}/.m2/repository by default). This cache allows Maven to avoid downloading the same artifacts repeatedly. You can customize the location of this repository by specifying a &lt;localRepository&gt; element in your user settings.xml file. The settings.xml file lives either in ${maven.home}/conf (global settings) or ${user.home}/.m2 (user‑specific settings), and its values are merged with user settings taking precedence.</p><p>A project’s pom.xml always points to remote repositories defined in the Super POM or in the project itself. When you declare a dependency, Maven first checks the local .m2 repository; if the artifact is missing, it downloads it from the specified remote repository (by default, the Central Repository at https://repo.maven.apache.org/maven2). The .m2/repository directory is therefore critical for builds – deleting it forces Maven to download all dependencies again, which is occasionally useful when clearing corrupted caches. The local repository also stores artifacts you install via mvn install, making them available for other projects on the same machine.</p><h4>Maven Build Lifecycle and Dependency Scopes</h4><p>Maven automates builds using lifecycles. The default lifecycle handles compiling, testing, packaging and deploying; the clean lifecycle removes previous build artifacts; the site lifecycle generates documentation.</p><p>Executing a phase triggers all preceding phases, e.g., running mvn package will run validate, compile, test and package. The main phases of the default lifecycle are:-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/976/1*9FBDBlYEaQkitoacro6XfQ.png" /></figure><pre>// Run one of phase using below. This automatically runs all preceding phases (validate → install).<br>mvn install</pre><pre>// Other phases <br>- mvn clean<br>pre-clean, clean, post-clean - Deletes previously built files like target/<br><br>- mvn site<br>pre-site, site, post-site, site-deploy - Generates and publishes site documentation<br></pre><p>Dependencies in Maven have scopes that control where and when they are used. The Maven dependency mechanism defines six scopes :-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1009/1*p3QACRHFLp-td6LzEKhAnA.png" /></figure><pre>// Each of these below phases trigger different secitons of POM file<br><br>validate → compile → test → package → verify → install → deploy</pre><pre>// Where does each section of POM file come in to play in maven phase <br>| Section                            | Comes into Play                                                   | Description                                                                                                                                               |<br>| ---------------------------------- | ----------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- |<br>| **`&lt;dependencies&gt;`**               | During `compile`, `test`, `package`, `install`, etc.              | Maven resolves and downloads dependencies **before** any relevant phase begins. Example: `JUnit` in `&lt;scope&gt;test&lt;/scope&gt;` is used only during `mvn test`. |<br>| **`&lt;build&gt;`**                      | During `compile`, `package`, etc.                                 | Defines build-specific settings like where compiled files go or which plugins to run.                                                                     |<br>| **`&lt;plugins&gt;`** (inside `&lt;build&gt;`) | Any relevant lifecycle phase like `compile`, `package`, `install` | These are tied to lifecycle phases. E.g., `maven-compiler-plugin` runs during `compile`, and `maven-jar-plugin` runs during `package`.                    |<br>| **`&lt;profiles&gt;`**                   | When a profile is activated (e.g., `-Pdev`)                       | You define environment-specific settings. Used to conditionally override dependencies, plugins, properties.                                               |<br>| **`&lt;properties&gt;`**                 | Resolved during entire build                                      | Acts as variables usable across the POM, useful for reusability and version management.                                                                   |<br>| **`&lt;repositories&gt;`**               | During dependency resolution                                      | If Maven needs to fetch a dependency from a custom repository instead of Maven Central.                                                                   |<br>| **`&lt;reporting&gt;`**                  | When running reporting goals like `mvn site`                      | Used for generating documentation and reports like JUnit test reports or code coverage.                                                                   |<br>| **`&lt;modules&gt;`**                    | When building a **multi-module** project                          | Specifies submodules that are part of the overall project. Triggered when building the parent project.                                                    |</pre><pre>// Types of file types in Java and their usage<br><br>| Type            | Stands For              | Used For                                                   | Contains                                                 |<br>| --------------- | ----------------------- | ---------------------------------------------------------- | -------------------------------------------------------- |<br>| **JAR**         | Java ARchive            | Standard Java applications, libraries                      | `.class` files, `META-INF`, config files, libraries      |<br>| **WAR**         | Web Application ARchive | Web applications (Servlets, JSPs, etc.)                    | Everything in a JAR **plus** `WEB-INF`, `web.xml`, JSPs  |<br>| **EAR**         | Enterprise ARchive      | Enterprise apps using EJBs or combining multiple WARs/JARs | WARs + JARs + EJBs + application.xml                     |<br>| **APK**         | Android Package         | Android applications                                       | Compiled Java/Kotlin code, resources, manifest, XML      |<br>| **AAR**         | Android ARchive         | Android library packages                                   | Similar to JARs but includes Android-specific components |<br>| **RSP**         | Response File           | (Rare) Used with some tools for automation                 | List of command-line arguments                           |<br>| **ZIP**/**TAR** | General archive         | Used for packaging anything                                | Not Java-specific but used sometimes                     |<br>| **POM**         | Project Object Model    | Maven project metadata                                     | XML format describing the project                        |</pre><p>Understanding scopes helps you avoid bloated classpaths and ensures that production code does not depend on test libraries. Maven also supports dependency management sections for centralizing version numbers across multiple modules.</p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;org.springframework&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-core&lt;/artifactId&gt;<br>    &lt;version&gt;5.3.27&lt;/version&gt;<br>    &lt;scope&gt;compile&lt;/scope&gt; &lt;!-- Or runtime, test, etc. --&gt;<br>&lt;/dependency&gt;</pre><p>Besides these, below files are generated during build process:-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*CmwYR6Lu3cqGpGqXF5sTow.png" /></figure><h4>Conclusion</h4><p>Understanding the structure of a Maven POM, the purpose of the .m2 repository, the build lifecycle and dependency scopes is essential for managing Java projects effectively. Armed with these tools, intermediate Java developers can build reproducible, modular applications with confidence.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8db5b5d92244" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular — What’s new in V20 ?]]></title>
            <link>https://medium.com/@dnrvec/angular-whats-new-in-v20-da9bdb0315ab?source=rss-3c8a25e4419c------2</link>
            <guid isPermaLink="false">https://medium.com/p/da9bdb0315ab</guid>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Naveen]]></dc:creator>
            <pubDate>Wed, 23 Jul 2025 03:03:12 GMT</pubDate>
            <atom:updated>2025-07-23T03:03:12.401Z</atom:updated>
            <content:encoded><![CDATA[<h3>Angular — What’s new in V20 ?</h3><p>We will try exploring few of new features from Angular v20</p><blockquote><strong>Zoneless Change Detection ( Experimental )</strong></blockquote><p>Going zoneless in Angular means running your application without relying on NgZone for change detection. This is a major shift introduced alongside Angular&#39;s Signals-based reactivity model, especially as of Angular v17+ and Angular 20.</p><p><strong><em>What is ngZone ?</em></strong></p><p>Angular traditionally uses Zone.js to patch all async APIs (e.g., setTimeout, XHR, Promise, etc.) to automatically trigger change detection after every async task.</p><p><strong><em>Problems with </em></strong><strong><em>NgZone:</em></strong></p><ul><li><strong>Performance overhead:</strong> It runs change detection on <strong>every async operation</strong>, even if the DOM doesn’t need updating.</li><li><strong>Debugging complexity:</strong> Hard to trace what triggered change detection.</li><li><strong>Inefficient for reactive UIs:</strong> With reactive primitives like <strong>signals</strong>, Angular can track only what’s needed — NgZone becomes redundant.</li></ul><p><strong><em>What is Zoneless?</em></strong></p><p>Zoneless Angular apps opt out of NgZone, and instead use fine-grained change detection via:</p><ul><li>Signals</li><li>Component-level effects</li><li>Manual detectChanges() (when needed)</li></ul><p>With experimental zoneless feature, Angular has signals and event-based reactivity to manage change detection paving for zoneless architecture.</p><pre>// Remove zone.js<br><br>import { provideZoneChangeDetection } from &#39;@angular/core&#39;;<br><br>bootstrapApplication(AppComponent, {<br>  providers: [<br>    provideZoneChangeDetection(&#39;noop&#39;) // disables Zone.js<br>  ]<br>});<br></pre><p><strong><em>Benefits:</em></strong></p><p>⚡ <strong>Better performance</strong> — Eliminates global change detection for every async task.</p><p>📦 <strong>Smaller bundle size</strong> — No need to include Zone.js.</p><p>🎯 <strong>Fine-grained reactivity</strong> — With signals, only affected components re-render.</p><p>🧪 <strong>More predictable behavior</strong> — You know exactly when and why change detection runs.</p><p>🔍 <strong>Easier debugging</strong> — Less magic from patched async APIs.</p><p>🔧 <strong>Better suited for micro-frontends</strong> — Avoids global side effects caused by Zone.js.</p><blockquote><strong>Signal-Based Reactivity (Stable)</strong></blockquote><p>Signals are a new primitive for managing reactive state, providing a <em>predictable</em> and <em>efficient</em> data flow.</p><p>Most signal APIs (including linkedSignal, effect, and resource streaming APIs) are now stable and fully supported, making this the recommended way to build reactive apps in Angular 20.</p><p>They provide <strong>fine-grained, performant, and predictable</strong> change detection — a huge step forward from traditional @Input, @Output, and RxJS</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/931/1*yKsAAVlnHmoY8tXwsQRLxg.png" /></figure><pre><br>import { signal, computed } from &#39;@angular/core&#39;;<br><br>const count = signal(0);<br>const double = computed(() =&gt; count() * 2);<br><br>count.set(5);<br>console.log(double()); // 10</pre><pre>// computed() – creates a derived signal<br>readonly doubleCount = computed(() =&gt; this.count() * 2);<br><br>// effect() – runs side effects when signals change<br>effect(() =&gt; {<br>  console.log(`New count: ${this.count()}`);<br>});</pre><p><strong><em>Benefits:-</em></strong></p><p>⚡ <strong>Fast</strong> — Only updates parts of the DOM that depend on the changed signal</p><p>🔍 <strong>Trackable</strong> — Easy to trace which state change caused a UI update</p><p>♻️ <strong>Reusable</strong> — You can share signals across components/services</p><p>🧘 <strong>Zoneless compatible</strong> — Works perfectly without NgZone</p><p>🧠 <strong>Synchronous</strong> — Simpler mental model than RxJS streams</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/907/1*sBmjNcFeKUoXkj4GeFw3xg.png" /></figure><blockquote><strong>Hydration Enhancements</strong></blockquote><p><strong>Hydration </strong>is the process where Angular takes the HTML rendered on the server and “activates” it on the client, attaching event listeners and making the app interactive — without re-rendering the DOM.</p><p><strong>Without hydration:</strong></p><ul><li>Angular re-renders everything from scratch.</li><li>The user sees the same HTML twice (wasted work).</li><li>DOM is replaced, potentially causing flicker or layout shift.</li></ul><p><strong>With hydration:</strong></p><ul><li>Angular <strong>reuses the server-rendered DOM</strong>.</li><li>Adds interactivity without re-rendering.</li><li>Faster, smoother user experience.</li></ul><p>Angular has evolved its hydration strategy, making it <strong>more reliable, faster, and customizable</strong>.</p><p><strong>Angular 17:</strong></p><ul><li>Introduced <strong>partial hydration</strong> for basic components.</li><li>Started using <strong>hydration markers</strong> in HTML to detect rehydration needs.</li></ul><p><strong>Angular 19:</strong></p><ul><li>Supported <strong>deferred blocks</strong> (@defer) and <strong>control flow</strong> (@if, @for) with hydration.</li></ul><p><strong>Angular 20:</strong></p><ul><li><strong>Improved granularity and customization</strong> with:</li><li>Better support for @defer + hydration.</li><li>Fixes for edge cases like form inputs, bindings, and dynamic content.</li><li>Configurable hydration strategies.</li></ul><pre>// Hydration is automatically enabled when using Angular Universal with SSR.<br>import { provideClientHydration } from &#39;@angular/platform-browser&#39;;<br><br>bootstrapApplication(AppComponent, {<br>  providers: [<br>    provideClientHydration({<br>      deferBlock: true // Only hydrate @defer blocks when they appear<br>    })<br>  ]<br>});</pre><pre>// Example<br>// Angular ensures the placeholder is rendered on server, <br>// and the profile component hydrates only when userLoaded is true<br>@defer (when userLoaded; loading) {<br>  &lt;app-user-profile /&gt;<br>}<br>@placeholder {<br>  &lt;p&gt;Loading...&lt;/p&gt;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/991/1*nPZ9AxwtPI1zPbslVXZgKQ.png" /></figure><blockquote><strong>Stabilized control flow</strong></blockquote><p>Angular has traditionally used structural directives like *ngIf, *ngFor, *ngSwitch.</p><p>Angular compiles these control blocks into <strong>efficient low-level instructions</strong> — even more optimized than structural directives like *ngIf and *ngFor.</p><p>They also support <strong>hydration</strong> in Angular Universal and <strong>deferred loading</strong> via @defer.</p><pre>// New way<br><br>@if (condition) {<br>  &lt;p&gt;It’s true!&lt;/p&gt;<br>} @else {<br>  &lt;p&gt;It’s false.&lt;/p&gt;<br>}<br><br>@for (item of items; track item.id) {<br>  &lt;div&gt;{{ item.name }}&lt;/div&gt;<br>}<br><br>@switch (type) {<br>  @case (&#39;cat&#39;) { }<br>  @case (&#39;dog&#39;) { }<br>  @default { ❓ }<br>}</pre><pre>// destructuring and index<br>@for ((user, i) of users) {<br>  &lt;div&gt;{{ i + 1 }}. {{ user.name }}&lt;/div&gt;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/973/1*DYSDS_tnV1xrPuvoetFncA.png" /></figure><p><strong>Angular 17:</strong></p><ul><li><strong>New syntax introduced</strong>:</li></ul><p>-@if / @else</p><p>-@for (item of items)</p><p>-@switch / @case / @default</p><ul><li>Initially available only in <strong>standalone components</strong></li><li>Required explicit import from @angular/common</li><li>Was in <strong>developer preview</strong> — not recommended for production</li></ul><p><strong>Angular 19:</strong></p><ul><li>Control flow now worked better with Signals, @defer blocks, Zoneless apps</li></ul><p><strong>Angular 20:</strong></p><ul><li>Control flow syntax is now <strong>stable and fully supported</strong></li><li>Supports <strong>nested blocks</strong>, <strong>trackBy</strong>, and <strong>destructuring</strong></li><li>Fully integrated with <strong>hydration</strong>, <strong>defer</strong>, and <strong>signals</strong></li><li>No preview, works in both <strong>standalone and NgModule-based components</strong></li></ul><blockquote><strong>Chrome DevTools Integration</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1011/1*gOcQow_rquUoojfqPTSn-Q.png" /></figure><p><strong>Resources:-</strong></p><ul><li><a href="https://blog.angular.dev/announcing-angular-v20-b5c9c06cf301">Announcing Angular v20</a></li><li><a href="https://www.syncfusion.com/blogs/post/whats-new-in-angular-20/amp">What&#39;s New in Angular 20?</a></li></ul><p><a href="https://blog.ninja-squad.com/2025/05/28/what-is-new-angular-20.0/">https://blog.ninja-squad.com/2025/05/28/what-is-new-angular-20.0/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=da9bdb0315ab" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NLPs & LLMs — Where to start ?]]></title>
            <link>https://medium.com/@dnrvec/nlps-llms-where-to-start-0663086e2ba0?source=rss-3c8a25e4419c------2</link>
            <guid isPermaLink="false">https://medium.com/p/0663086e2ba0</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Naveen]]></dc:creator>
            <pubDate>Mon, 07 Jul 2025 03:38:38 GMT</pubDate>
            <atom:updated>2025-07-07T03:38:38.821Z</atom:updated>
            <content:encoded><![CDATA[<h3>NLPs &amp; LLMs — Where to start ?</h3><p>Is your app in need of LLMs or NLP ? Do we need to pay for our apps ?</p><p><em>As you start building AI-powered applications, it’s important to weigh several key factors — especially cost, which can rise quickly if not fully accounted for. It may be prudent to begin with NLP tools or local LLMs, then evaluate open-source and closed-source models based on your evolving needs</em></p><h3>NLPs</h3><h4>Paid NLP APIs / Aggregators</h4><blockquote><strong>Hugging Face Inference API</strong></blockquote><ul><li><strong>Best for:</strong> Trying hosted transformer models.</li><li><strong>Free</strong>: Yes (limited).</li><li><strong>Paid</strong>: Starting at $0.06 per second for dedicated endpoints.</li></ul><pre>from transformers import pipeline<br>pipe = pipeline(&quot;ner&quot;, model=&quot;dslim/bert-base-NER&quot;)<br>print(pipe(&quot;Hugging Face is in New York City.&quot;))</pre><blockquote><strong>Cohere NLP API</strong></blockquote><ul><li>Best for: Classification, embeddings, generation.</li><li>Free: Trial credits.</li><li>Paid: Usage-based pricing.</li></ul><blockquote><strong>DeepL API</strong></blockquote><ul><li>Best for: High-quality translation (alternative to Google Translate).</li><li>Free: Yes (limited).</li><li>Paid: Monthly subscription</li></ul><h4>Cloud NLP APIs (Free Tiers Available)</h4><p>Quick, no-hosting solutions for tasks like sentiment, entities, translation, etc.</p><blockquote><strong>Google Cloud Natural Language API</strong></blockquote><ul><li><strong>Best for</strong>: Entity detection, syntax, sentiment, classification.</li><li><strong>Free tier</strong>: Yes (5000 units/month).</li><li><strong>Pricing</strong>: Pay-as-you-go.</li></ul><pre>from google.cloud import language_v1<br>client = language_v1.LanguageServiceClient()<br>document = language_v1.Document(content=&quot;Python is awesome&quot;, type_=language_v1.Document.Type.PLAIN_TEXT)<br>sentiment = client.analyze_sentiment(document=document).document_sentiment<br>print(sentiment.score)</pre><blockquote><strong>AWS Comprehend</strong></blockquote><ul><li><strong>Best for:</strong> Enterprise NLP (entities, topics, sentiment).</li><li><strong>Free tier:</strong> Yes (first 12 months).</li></ul><pre>import boto3<br>client = boto3.client(&#39;comprehend&#39;)<br>response = client.detect_sentiment(Text=&#39;I love NLP.&#39;, LanguageCode=&#39;en&#39;)<br>print(response[&#39;Sentiment&#39;])</pre><blockquote><strong>Microsoft Azure Text Analytics</strong></blockquote><ul><li>Best for: Multilingual NLP, PII detection.</li><li>Free: Yes (trial).</li><li>Paid: Usage-based pricing.</li></ul><h4>Local / Open-Source NLP Libraries</h4><p>These run <strong>on your machine</strong>, require no internet, and are great for deterministic or statistical NLP tasks.</p><blockquote><strong>spaCy</strong></blockquote><ul><li><strong>Best for:</strong> Production NLP (tokenization, NER, POS, dependency parsing).</li><li><strong>Free</strong>: Yes (MIT License).</li></ul><pre>import spacy<br>nlp = spacy.load(&quot;en_core_web_sm&quot;)<br>doc = nlp(&quot;John lives in New York.&quot;)<br>print([(ent.text, ent.label_) for ent in doc.ents])</pre><blockquote><strong>Stanza (Stanford NLP)</strong></blockquote><ul><li><strong>Best for</strong>: Academic-grade NLP with multilingual support.</li><li><strong>Free</strong>: Yes (Apache 2.0).</li></ul><pre>import stanza<br>stanza.download(&#39;en&#39;)<br>nlp = stanza.Pipeline(&#39;en&#39;)<br>doc = nlp(&quot;Barack Obama was born in Hawaii.&quot;)<br>print(doc.entities)</pre><blockquote><strong>Flair</strong></blockquote><ul><li><strong>Best for</strong>: Easy sequence labeling, embeddings.</li><li><strong>Free</strong>: Yes (MIT License).</li></ul><pre>from flair.models import SequenceTagger<br>from flair.data import Sentence<br>tagger = SequenceTagger.load(&quot;ner&quot;)<br>sentence = Sentence(&quot;Angela Merkel lives in Berlin.&quot;)<br>tagger.predict(sentence)<br>print(sentence.to_dict())</pre><blockquote><strong>Haystack</strong></blockquote><ul><li><strong>Best for</strong>: Local RAG pipelines, semantic search, QA.</li><li><strong>Free</strong>: Yes.</li><li>supports vector DBs like FAISS, Chroma</li></ul><pre>pip install farm-haystack</pre><blockquote><strong>GPT4All / llama.cpp</strong></blockquote><ul><li><strong>Best for</strong>: Running quantized language models with NLP capabilities.</li><li><strong>Free</strong>: Yes (MIT license).</li></ul><blockquote><strong>When to use what</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jCRmyGzj_3NT63f-zF_H2w.png" /></figure><h3>LLMs</h3><p>Lets look at pricing for few of LLMs as start using them.</p><h4>Paid Cloud LLM APIs</h4><p>Most have a <strong>free tier</strong>, but beyond that, they are <strong>pay-as-you-go</strong>.</p><blockquote><strong>OpenAI (GPT-3.5 / GPT-4 / GPT-4o)</strong></blockquote><ul><li><strong>Best for</strong>: General-purpose reasoning, code generation, chatbots, agents.</li><li><strong>Free tier</strong>: Yes (limited via ChatGPT, API has trial credits).</li><li><strong>Pricing</strong>: Starts at ~$0.50 per 1 million tokens (GPT-3.5), GPT-4o is faster and cheaper than previous GPT-4 versions.</li></ul><pre>import openai<br><br>openai.api_key = &quot;your-openai-key&quot;<br><br>response = openai.ChatCompletion.create(<br>    model=&quot;gpt-4o&quot;,<br>    messages=[{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;What&#39;s the capital of North Carolina?&quot;}]<br>)<br><br>print(response.choices[0].message[&quot;content&quot;])</pre><blockquote><strong>Anthropic (Claude 3 Family)</strong></blockquote><ul><li><strong>Best for</strong>: Long-context use cases (can handle 200K+ tokens), ethical alignment.</li><li><strong>Models</strong>: Claude 3 Opus (best), Sonnet (balanced), Haiku (fastest).</li><li><strong>Pricing</strong>: From $0.25 to $15 per million tokens.</li><li><strong>Free tier</strong>: No API free tier, but free via Claude.ai chat interface.</li></ul><pre>import anthropic<br><br>client = anthropic.Anthropic(api_key=&quot;your-anthropic-key&quot;)<br><br>response = client.messages.create(<br>    model=&quot;claude-3-sonnet-20240229&quot;,<br>    max_tokens=100,<br>    messages=[{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;Summarize about NC coastal line.&quot;}]<br>)<br><br>print(response.content[0].text)</pre><blockquote><strong>Google Gemini (1.5 Pro)</strong></blockquote><ul><li><strong>Best for</strong>: Multimodal tasks, long-context chat, integration with Google ecosystem.</li><li><strong>Free tier</strong>: Yes, limited usage in Google AI Studio.</li><li><strong>Usage via</strong>: google.generativeai Python SDK or REST.</li></ul><pre>import google.generativeai as genai<br><br>genai.configure(api_key=&quot;your-google-api-key&quot;)<br>model = genai.GenerativeModel(&#39;gemini-1.5-pro-latest&#39;)<br><br>response = model.generate_content(&quot;Explain Generateive AI in simple terms.&quot;)<br>print(response.text)</pre><blockquote><strong>Together AI (Aggregator API)</strong></blockquote><ul><li><strong>Best for</strong>: Accessing open models like LLaMA, Mistral, Mixtral cheaply.</li><li><strong>Free tier</strong>: Yes (trial credits).</li><li><strong>Models</strong>: LLaMA-2/3, Mistral 7B, Mixtral, etc.</li></ul><pre>import openai<br><br>openai.api_key = &quot;your-together-api-key&quot;<br>openai.api_base = &quot;https://api.together.xyz/v1&quot;<br><br>response = openai.ChatCompletion.create(<br>    model=&quot;mistralai/Mixtral-8x7B-Instruct-v0.1&quot;,<br>    messages=[{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;Write a haiku about the sea&quot;}]<br>)<br><br>print(response.choices[0].message[&quot;content&quot;])</pre><h4>Free/Public APIs and Platforms</h4><blockquote><strong>Hugging Face Inference API</strong></blockquote><ul><li><strong>Best for</strong>: Experimentation with open-source models (GPT-J, Falcon, etc.).</li><li><strong>Free</strong>: Yes (rate-limited).</li><li><strong>Interface</strong>: REST or Python transformers.</li></ul><pre>from transformers import pipeline<br><br>pipe = pipeline(&quot;text-generation&quot;, model=&quot;EleutherAI/gpt-neo-1.3B&quot;)<br>result = pipe(&quot;Translate to French: Hello, how are you?&quot;, max_new_tokens=30)<br>print(result[0][&#39;generated_text&#39;])</pre><blockquote><strong>OpenRouter (Aggregator Gateway)</strong></blockquote><ul><li><strong>Best for</strong>: Trying Claude, GPT, LLaMA, Mistral models via one API endpoint.</li><li><strong>Free</strong>: Yes (optional paid models).</li><li><strong>Compatible with</strong>: OpenAI SDK.</li></ul><pre>import openai<br><br>openai.api_key = &quot;your-openrouter-key&quot;<br>openai.api_base = &quot;https://openrouter.ai/api/v1&quot;<br><br>response = openai.ChatCompletion.create(<br>    model=&quot;mistralai/mistral-7b-instruct&quot;,<br>    messages=[{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;Give me a productivity tip&quot;}]<br>)<br>print(response.choices[0].message[&quot;content&quot;])</pre><h4>Self-Hosted LLMs (Run Locally)</h4><p>These are open-source models you can run on your machine using tools like Ollama, LM Studio, or directly with transformers.</p><blockquote><strong>Ollama (Easiest Way to Run LLMs Locally)</strong></blockquote><ul><li><strong>Supports</strong>: LLaMA 3, Mistral, Phi-3, Gemma, and more.</li><li><strong>Free</strong>: Yes (just need enough RAM/GPU).</li><li><strong>Command Line / REST API / Python SDK</strong></li></ul><pre>brew install ollama     # macOS<br>ollama run llama3       # downloads and runs the model<br><br>// Usage<br><br>import requests<br><br>res = requests.post(&quot;http://localhost:11434/api/generate&quot;, json={<br>    &quot;model&quot;: &quot;llama3&quot;,<br>    &quot;prompt&quot;: &quot;Explain recursion&quot;,<br>})<br>print(res.json()[&#39;response&#39;])</pre><blockquote><strong>Hugging Face Transformers (Custom Local Models)</strong></blockquote><ul><li><strong>Best for</strong>: Fine-tuning or full local control.</li><li><strong>Requirement</strong>: GPU for fast inference, but small models run on CPU.</li></ul><pre>from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline<br><br>model = AutoModelForCausalLM.from_pretrained(&quot;mistralai/Mistral-7B-Instruct-v0.1&quot;)<br>tokenizer = AutoTokenizer.from_pretrained(&quot;mistralai/Mistral-7B-Instruct-v0.1&quot;)<br>pipe = pipeline(&quot;text-generation&quot;, model=model, tokenizer=tokenizer)<br><br>print(pipe(&quot;Explain the solar system.&quot;, max_new_tokens=100)[0][&#39;generated_text&#39;])</pre><blockquote><strong>When to use what ?</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*qnw9teed8LeMI4RA0zluug.png" /></figure><h3>Few Differences on different approaches</h3><h4><strong>Hugging Face Transformers (Local Models) vs Hugging Face Inference API</strong></h4><blockquote><strong>Hugging Face Transformers (Local Models)</strong></blockquote><p><em>“Run the model </em><strong><em>on your machine</em></strong><em> using </em><em>transformers.”</em></p><p><em>What it is:</em></p><ul><li>You <strong>download</strong> a model and run it locally (CPU/GPU).</li><li>Uses transformers, torch, or accelerate behind the scenes.</li><li>No external API requests — <strong>fully offline</strong> after download.</li></ul><p><em>Use Case:</em></p><ul><li>Full control, no API cost.</li><li>Ideal for privacy-sensitive or offline applications.</li><li>Fine-tuning and custom pipelines.</li></ul><pre>from transformers import pipeline<br><br>pipe = pipeline(&quot;text-generation&quot;, model=&quot;mistralai/Mistral-7B-Instruct-v0.1&quot;)<br>print(pipe(&quot;What is a black hole?&quot;, max_new_tokens=50))</pre><blockquote><strong>Hugging Face Inference API</strong></blockquote><p><em>“Access a model hosted </em><strong><em>on Hugging Face’s servers</em></strong><em> via web API.”</em></p><p><em>What it is:</em></p><ul><li>You send a request to Hugging Face’s <strong>cloud</strong> to run the model.</li><li>Hugging Face handles compute (no local GPU required).</li><li>Rate-limited for free accounts; pay-as-you-go beyond that.</li></ul><p><em>Use Case:</em></p><ul><li>Quick prototyping or when you don’t want to run models locally.</li><li>Ideal for web apps without GPU resources.</li></ul><pre>import requests<br><br>API_URL = &quot;https://api-inference.huggingface.co/models/gpt2&quot;<br>headers = {&quot;Authorization&quot;: &quot;Bearer YOUR_HF_TOKEN&quot;}<br><br>response = requests.post(API_URL, headers=headers, json={&quot;inputs&quot;: &quot;What is gravity?&quot;})<br>print(response.json())</pre><h4>OpenRouter and Together AI</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/997/1*fQSHsAuY9SfrwA4Ixh_f4w.png" /></figure><pre># Open ROuter<br>openai.api_base = &quot;https://openrouter.ai/api/v1&quot;<br>openai.api_key = &quot;your-openrouter-key&quot;<br><br>openai.ChatCompletion.create(<br>  model=&quot;anthropic/claude-3-opus&quot;,  # You can also use Mistral, GPT-4 etc.<br>  messages=[{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;Explain entropy&quot;}]<br>)<br><br># Together<br><br>openai.api_base = &quot;https://api.together.xyz/v1&quot;<br>openai.api_key = &quot;your-together-key&quot;<br><br>openai.ChatCompletion.create(<br>  model=&quot;mistralai/Mixtral-8x7B-Instruct-v0.1&quot;,<br>  messages=[{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;Explain entropy&quot;}]<br>)</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0663086e2ba0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LLMs & Frameworks]]></title>
            <link>https://medium.com/@dnrvec/llms-frameworks-53b6e6140396?source=rss-3c8a25e4419c------2</link>
            <guid isPermaLink="false">https://medium.com/p/53b6e6140396</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[large-language-models]]></category>
            <dc:creator><![CDATA[Naveen]]></dc:creator>
            <pubDate>Mon, 30 Jun 2025 02:00:04 GMT</pubDate>
            <atom:updated>2025-06-30T02:00:04.315Z</atom:updated>
            <content:encoded><![CDATA[<p>“There’s a lot to learn in the world of LLMs and their associated frameworks, especially with how rapidly things evolve. This blog aims to give you a starting point on your journey into Generative AI.”</p><blockquote><strong>Large Language Models</strong></blockquote><ul><li>These are <strong>the raw models</strong> that do the text understanding/generation</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/988/1*akL_i9GC66c4e5O5tl90ag.png" /></figure><blockquote><strong>Frameworks</strong></blockquote><ul><li>Using models above, we can use below frameworks to build apps</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/988/1*ztDEB_QRc-qsKkK5WxWcvw.png" /></figure><blockquote><strong>Platform/Model Hosts</strong></blockquote><ul><li>These hosts APIs required to connect to LLMs</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/935/1*T2hCHV-JFLa7iA7Z2u4cCA.png" /></figure><blockquote><strong>How do they work together ?</strong></blockquote><ul><li>Lets see how all these come together</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/981/1*HJ8g1qjekBTVa_KL2FiacA.png" /></figure><blockquote><strong>When to use what ?</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/938/1*lyDfmCy9WGGkPz60LuW8Ag.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/922/1*WCcO0RU_njYpmFeZU0yEgQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*raacgDQ9LHsctadYfTvP1A.png" /></figure><p><strong>Open source LLMs</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Asp1T5rxGoKK7We-Ler66g.png" /></figure><p><strong>Closed/Proprietary LLMs</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/990/1*yQ9R6ED9iWhoNTxZ05forQ.png" /></figure><blockquote><strong>Analogy </strong>— Lets look at couple of examples to understand how all these come together.</blockquote><h4><strong><em>Scenario 1:- LLM Powered Restaurant assistant</em></strong></h4><p><strong>— LLaMA, GPT, Mistral, etc. = The Chef (LLM Model)</strong></p><ul><li>These are raw intelligence.</li><li>They know how to respond to prompts like “cook pasta” or “summarize this text.”</li><li>They don’t know your kitchen, menu, or rules yet.</li><li>Example: LLaMA 3 is a great chef, but needs instructions.</li></ul><p><em>“Just give me the brain that can understand and talk.”</em></p><p>— <strong>LangChain = The Kitchen Manager / Workflow Planner (Framework)</strong></p><ul><li>Organizes the chef’s work:</li><li>Fetches recipes from the database (tool).</li><li>Sends orders to the chef (LLM).</li><li>Logs steps.</li><li>Decides what to do based on user questions.</li><li>Adds memory, tool use, chaining, retries, etc.</li></ul><p><em>“Here’s how our assistant uses the chef + fridge + recipes to make a dish.”</em></p><p><strong>— LlamaIndex = The Recipe Librarian (Data Indexing Framework)</strong></p><ul><li>Knows how to organize and query <strong>your documents</strong> (PDFs, DBs, websites).</li><li>When the user asks something like “What’s the allergen policy?”, LlamaIndex:</li><li>Retrieves relevant docs.</li><li>Feeds them to the chef via LangChain.</li><li>Thinks in terms of <strong>retrieval-augmented generation (RAG)</strong>.</li></ul><p><em>“Let me look through our 500-page handbook and give you the most relevant info.”</em></p><p><strong>— Hugging Face = Supermarket + Chef Rental (Platform + Hub)</strong></p><ul><li>Lets you get the chef (LLMs like LLaMA, Mistral, Falcon).</li><li>Lets you run models in the cloud (via Inference API or Spaces).</li><li>You can also download tools, datasets, and pipelines.</li></ul><p><em>“Go here to hire a chef, get kitchen tools, or download ingredients.”</em></p><p><strong>— OpenAI API = Luxury Chef on Demand</strong></p><ul><li>Provides <strong>very smart chefs (GPT-4)</strong> via an API.</li><li>You don’t download the chef — just send requests like “make soup.”</li><li>High quality, paid access.</li></ul><p><em>“UberEats but for high-end chef brains.”</em></p><p><strong>— Ollama = Local Kitchen (Run Chefs on Your Laptop)</strong></p><ul><li>Lets you run <strong>open models like LLaMA or Mistral locally</strong>.</li><li>Great if you want privacy or offline capability.</li></ul><p><em>“Set up your own kitchen and hire your own open-source chef to stay with you.”</em></p><p><strong>— LangGraph, AutoGen = Executive Kitchen Team (Multi-Agent Frameworks)</strong></p><ul><li>Enable multiple agents working together</li><li>Planner agent, researcher agent, summarizer agent</li><li>Track long-term memory, message passing, retries</li></ul><p><em>“Head chef managing pastry chef, sous-chef, and servers.”</em></p><h4><strong><em>Scenario 2:- LLM Powered Travel assistant</em></strong></h4><p>I want to get things to do near Raleigh next week”</p><p>You want to ask your <strong>AI travel assistant</strong> this, and get relevant events, places, or recommendations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/1*yqm74ylEnnsbqxASNtU6wA.png" /></figure><p><strong>— The Concierge (LLM)</strong></p><p>Understands your request.</p><ul><li>Figures out:</li><li>“Raleigh” = city</li><li>“next week” = date range (July 1–7)</li><li>“things to do” = fetch local events, attractions</li></ul><p><em>“Sure! Let me check events and attractions in Boston next week.”</em></p><p><strong>— The Library (LlamaIndex)</strong></p><p>Concierge consults the <strong>guidebooks and local listings</strong> (your PDFs, websites, event APIs).</p><ul><li>Looks up: Ticketmaster, RSS feeds, City tourism websites</li></ul><p><em>“Let me check the events database for your dates…”</em></p><p><strong>— The Manager (LangChain)</strong></p><p>Behind the scenes, <strong>LangChain</strong> is telling the concierge:</p><ul><li>When to use tools</li><li>How to plan the steps</li><li>Whether to retry if something fails</li></ul><p><em>“If the user’s location is missing, ask again. If there’s no event data, fall back to general attractions.”</em></p><p><strong>— The Agency (OpenAI or Hugging Face)</strong></p><p>If your hotel doesn’t have a concierge, it <strong>calls in one remotely</strong>:</p><ul><li>Uses OpenAI API (like hiring GPT-4 remotely)</li><li>Or Hugging Face API (uses Mistral remotely)</li><li>Or Ollama (runs one locally on your own server)</li></ul><p><em>🛜 “Calling GPT-4 from the cloud…Or running Mistral on your laptop via Ollama”</em></p><p><strong>— The Team (LangGraph / AutoGen)</strong></p><p>For a complex request like:</p><p><em>“Plan a 3-day Boston trip, prioritize museums, but only outdoor stuff if it rains…”</em></p><p>You’d want:</p><ul><li>A planner agent</li><li>A weather checker</li><li>A tour recommender</li></ul><p>LangGraph handles that — like coordinating multiple hotel staff members to fulfill one complicated guest request.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1N1-mkJCfZm2q7fv" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1014/1*CarlBv4GLqUQjtePT30GQQ.png" /></figure><p>“Happy learning! There’s so much to explore and experiment with in the world of Generative AI — just like the early days of HTML. Looking forward to seeing many great implementations ahead.”</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=53b6e6140396" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java — Lets learn few features…Generics]]></title>
            <link>https://medium.com/@dnrvec/java-lets-learn-few-features-generics-a87f7695497b?source=rss-3c8a25e4419c------2</link>
            <guid isPermaLink="false">https://medium.com/p/a87f7695497b</guid>
            <category><![CDATA[java-generic]]></category>
            <dc:creator><![CDATA[Naveen]]></dc:creator>
            <pubDate>Sun, 22 Jun 2025 16:15:35 GMT</pubDate>
            <atom:updated>2025-06-22T16:15:35.163Z</atom:updated>
            <content:encoded><![CDATA[<h3>Java — Lets learn few features…Generics</h3><p>Let’s take a real-world scenario and build around it to explain <strong>Java Generics</strong> along with <strong>related Java concepts</strong> where generics are used. The idea is to build a comprehensive, relatable example while covering the breadth of generics in Java.</p><h4>Real-World Scenario: Online Grocery Store</h4><p>We’ll use an online grocery store example. The store deals with different types of products: fruits, vegetables, packaged items, etc. Each item has a price, a name, and sometimes expiry dates or categories.</p><h4>Java Concepts Covered:</h4><ul><li>Generic Classes</li><li>Generic Methods</li><li>Bounded Type Parameters</li><li>Wildcards (?, &lt;? extends T&gt;, &lt;? super T&gt;)</li><li>Generics with Collections (e.g., List&lt;T&gt;)</li><li>Inheritance and Generics</li><li>Custom Comparator with Generics</li><li>Type Erasure (brief mention)</li></ul><pre>public class Box&lt;T&gt; {<br>    private T item;<br><br>    public void setItem(T item) {<br>        this.item = item;<br>    }<br><br>    public T getItem() {<br>        return item;<br>    }<br>}<br><br>// Usage<br>Box&lt;String&gt; stringBox = new Box&lt;&gt;();<br>stringBox.setItem(&quot;Apple&quot;);<br><br>Box&lt;Integer&gt; weightBox = new Box&lt;&gt;();<br>weightBox.setItem(5); // e.g., 5 kg of rice</pre><blockquote><strong>Generic Method</strong></blockquote><pre>public class Utils {<br>    public static &lt;T&gt; boolean isEqual(T a, T b) {<br>        return a.equals(b);<br>    }<br>}<br><br>// Usage<br>boolean result = Utils.isEqual(&quot;Milk&quot;, &quot;Milk&quot;);  // true</pre><blockquote><strong>Bounded Type Parameters</strong></blockquote><p>Suppose we want to restrict types to only those that are Product or its subclasses.</p><pre>public class Product {<br>    String name;<br>    double price;<br><br>    // constructors, getters<br>}<br><br>public class Fruit extends Product {<br>    String type;<br>    // constructors, extra fields<br>}<br><br>public class Inventory&lt;T extends Product&gt; {<br>    private List&lt;T&gt; items = new ArrayList&lt;&gt;();<br><br>    public void addItem(T item) {<br>        items.add(item);<br>    }<br><br>    public double totalValue() {<br>        return items.stream().mapToDouble(Product::getPrice).sum();<br>    }<br>}<br>// Usage<br><br>Inventory&lt;Fruit&gt; fruitInventory = new Inventory&lt;&gt;();<br>fruitInventory.addItem(new Fruit(&quot;Apple&quot;, 2.5, &quot;Organic&quot;));</pre><blockquote><strong>Wildcards</strong></blockquote><p><em>a. Upper Bound (</em><em>&lt;? extends Product&gt;)</em></p><p>To read from a list of any product type safely:</p><pre>public static void printPrices(List&lt;? extends Product&gt; products) {<br>    for (Product p : products) {<br>        System.out.println(p.getPrice());<br>    }<br>}</pre><p>b. Lower Bound (&lt;? super Fruit&gt;)</p><p>To add fruits to a list that accepts any superclass of Fruit:</p><pre>public static void addFruit(List&lt;? super Fruit&gt; list) {<br>    list.add(new Fruit(&quot;Banana&quot;, 1.2, &quot;Cavendish&quot;));<br>}</pre><blockquote><strong>Generics with Collections</strong></blockquote><p>Collections like List&lt;T&gt;, Map&lt;K, V&gt;, Set&lt;T&gt; are generic.</p><pre>List&lt;Product&gt; cart = new ArrayList&lt;&gt;();<br>cart.add(new Fruit(&quot;Mango&quot;, 3.0, &quot;Alphonso&quot;));<br><br>Map&lt;String, List&lt;Product&gt;&gt; categoryMap = new HashMap&lt;&gt;();<br>categoryMap.put(&quot;Fruits&quot;, cart);</pre><blockquote><strong>Inheritance with Generics</strong></blockquote><pre>public class DiscountedBox&lt;T extends Product&gt; extends Box&lt;T&gt; {<br>    private double discount;<br><br>    public double getDiscountedPrice() {<br>        return getItem().getPrice() * (1 - discount);<br>    }<br>}</pre><blockquote><strong>Comparator with Generics</strong></blockquote><pre>// Sorting<br>public class ProductComparator&lt;T extends Product&gt; implements Comparator&lt;T&gt; {<br>    public int compare(T p1, T p2) {<br>        return Double.compare(p1.getPrice(), p2.getPrice());<br>    }<br>}<br><br>Collections.sort(productList, new ProductComparator&lt;&gt;());</pre><h4>Example</h4><pre>Inventory&lt;Fruit&gt; fruitInventory = new Inventory&lt;&gt;();<br>fruitInventory.addItem(new Fruit(&quot;Apple&quot;, 1.5, &quot;Organic&quot;));<br>fruitInventory.addItem(new Fruit(&quot;Orange&quot;, 2.0, &quot;Mandarin&quot;));<br><br>Inventory&lt;Vegetable&gt; vegInventory = new Inventory&lt;&gt;();<br>vegInventory.addItem(new Vegetable(&quot;Carrot&quot;, 0.9));<br><br>Utils.printPrices(fruitInventory.getItems()); // Using upper bound wildcard<br><br>List&lt;Product&gt; combined = new ArrayList&lt;&gt;();<br>combined.addAll(fruitInventory.getItems());<br>combined.addAll(vegInventory.getItems());<br><br>Collections.sort(combined, new ProductComparator&lt;&gt;());<br><br>DiscountedBox&lt;Fruit&gt; offer = new DiscountedBox&lt;&gt;();<br>offer.setItem(new Fruit(&quot;Kiwi&quot;, 2.5, &quot;Green&quot;));<br>offer.setDiscount(0.2); // 20% off</pre><h4>Why Generics Are Still Needed (Even With Streams and Lambdas)</h4><blockquote><strong>Streams use generics heavily</strong></blockquote><pre>List&lt;String&gt; names = List.of(&quot;Alice&quot;, &quot;Bob&quot;, &quot;Charlie&quot;);<br><br>names.stream()<br>     .filter(name -&gt; name.startsWith(&quot;A&quot;))<br>     .map(String::toUpperCase)<br>     .forEach(System.out::println);</pre><ul><li>Stream&lt;String&gt; here means the compiler knows what type it’s working with at each stage.</li><li>Without generics, you’d need manual casting and runtime checks — which generics save you from.</li></ul><blockquote><strong>Collections and APIs are generics-based</strong></blockquote><p>Even modern patterns like functional programming <strong>build on</strong> generics.</p><p>Example: Optional&lt;T&gt;, Function&lt;T, R&gt;, Predicate&lt;T&gt;, Comparator&lt;T&gt; — these are all <strong>generic interfaces</strong>.</p><pre>Optional&lt;Integer&gt; value = Optional.of(42);<br>Function&lt;String, Integer&gt; parseInt = Integer::parseInt;<br>Predicate&lt;String&gt; isLongName = name -&gt; name.length() &gt; 5;</pre><blockquote><strong>Custom Reusable Utilities Still Require Generics</strong></blockquote><p>Streams solve many cases for data processing, but when you write reusable, <strong>type-safe utilities</strong> or components — you need generics.</p><p>Example: sorting logic, custom data containers, utilities that work with multiple types.</p><pre>public static &lt;T extends Comparable&lt;T&gt;&gt; T max(List&lt;T&gt; list) {<br>    return list.stream().max(Comparator.naturalOrder()).orElse(null);<br>}</pre><blockquote><strong>Streams don’t eliminate type hierarchies</strong></blockquote><p>You still need:</p><ul><li>Generic classes (class Box&lt;T&gt;)</li><li>Bounded generics (&lt;T extends Product&gt;)</li><li>Wildcards (&lt;? extends T&gt;, &lt;? super T&gt;)</li><li>Inheritance and generic APIs</li></ul><p>None of that is replaced by streams — streams complement this by offering <strong>processing pipelines</strong>.</p><blockquote><strong>Real-World Frameworks Still Rely on Generics</strong></blockquote><p>Frameworks like:</p><ul><li><strong>Spring</strong> (e.g. JpaRepository&lt;T, ID&gt;)</li><li><strong>Jackson</strong> (e.g. TypeReference&lt;List&lt;MyClass&gt;&gt;)</li><li><strong>RxJava</strong>, <strong>Project Reactor</strong>, <strong>MapStruct</strong>, <strong>Guava</strong></li></ul><p>All use generics deeply for flexibility, reusability, and safety.</p><h4>Where Streams Do Reduce the Need for <em>Some</em> Generics</h4><blockquote><strong>Example 1: No need for utility classes like </strong><strong>ListUtils&lt;T&gt;</strong></blockquote><pre>// Before<br>public class ListUtils {<br>    public static &lt;T&gt; void print(List&lt;T&gt; list) {<br>        for (T item : list) System.out.println(item);<br>    }<br>}<br><br>// After<br>list.forEach(System.out::println);</pre><blockquote><strong>Example 2: Less need for custom filters or transformers</strong></blockquote><pre>// Before<br>public static &lt;T&gt; List&lt;T&gt; filter(List&lt;T&gt; list, Predicate&lt;T&gt; pred) { ... }<br><br>// After<br>list.stream().filter(pred).collect(Collectors.toList());</pre><h4><strong>Older utility-style generics</strong> vs <strong>modern Java with Streams and Lambdas</strong></h4><blockquote><strong>Filtering Items by Price</strong></blockquote><pre>// Before<br><br>public static &lt;T&gt; List&lt;T&gt; filter(List&lt;T&gt; list, Predicate&lt;T&gt; predicate) {<br>    List&lt;T&gt; result = new ArrayList&lt;&gt;();<br>    for (T item : list) {<br>        if (predicate.test(item)) {<br>            result.add(item);<br>        }<br>    }<br>    return result;<br>}<br><br>// Usage<br>List&lt;Product&gt; cheapItems = filter(products, p -&gt; p.getPrice() &lt; 10);<br><br>// After<br><br>List&lt;Product&gt; cheapItems = products.stream()<br>                                   .filter(p -&gt; p.getPrice() &lt; 10)<br>                                   .collect(Collectors.toList());</pre><blockquote><strong>Transforming Items (Map to Names)</strong></blockquote><pre>// Before<br><br>public static List&lt;String&gt; extractNames(List&lt;Product&gt; products) {<br>    List&lt;String&gt; names = new ArrayList&lt;&gt;();<br>    for (Product p : products) {<br>        names.add(p.getName());<br>    }<br>    return names;<br>}<br><br>// After<br>List&lt;String&gt; names = products.stream()<br>                             .map(Product::getName)<br>                             .collect(Collectors.toList());</pre><blockquote><strong>Sorting Products by Price</strong></blockquote><pre>// Before<br>Collections.sort(products, new Comparator&lt;Product&gt;() {<br>    public int compare(Product p1, Product p2) {<br>        return Double.compare(p1.getPrice(), p2.getPrice());<br>    }<br>});<br><br>// After<br>List&lt;Product&gt; sorted = products.stream()<br>                               .sorted(Comparator.comparing(Product::getPrice))<br>                               .collect(Collectors.toList());</pre><blockquote><strong>Finding the Most Expensive Product</strong></blockquote><pre>// Before<br>public static Product findMax(List&lt;Product&gt; list) {<br>    if (list.isEmpty()) return null;<br>    Product max = list.get(0);<br>    for (Product p : list) {<br>        if (p.getPrice() &gt; max.getPrice()) {<br>            max = p;<br>        }<br>    }<br>    return max;<br>}<br><br>// After<br>Optional&lt;Product&gt; max = products.stream()<br>                                .max(Comparator.comparing(Product::getPrice));</pre><blockquote><strong>Grouping Products by Name</strong></blockquote><pre>// Before<br>public static Map&lt;String, List&lt;Product&gt;&gt; groupByName(List&lt;Product&gt; products) {<br>    Map&lt;String, List&lt;Product&gt;&gt; map = new HashMap&lt;&gt;();<br>    for (Product p : products) {<br>        map.computeIfAbsent(p.getName(), k -&gt; new ArrayList&lt;&gt;()).add(p);<br>    }<br>    return map;<br>}<br><br>// After<br>Map&lt;String, List&lt;Product&gt;&gt; grouped = products.stream()<br>                                             .collect(Collectors.groupingBy(Product::getName));</pre><h4>When to Still Use Utility-Style Generics</h4><ul><li>To <strong>abstract logic</strong> that’s used in multiple places.</li><li>To handle <strong>types outside of stream context</strong> (e.g., external APIs, data structures).</li><li>When working with <strong>non-streamable</strong> inputs (arrays, trees, etc.).</li><li>For <strong>backward compatibility</strong> or unit testing business logic.</li><li>When using <strong>custom containers</strong> or <strong>libraries</strong> that aren’t stream-friendly.</li><li>When needing <strong>custom reusable methods</strong> (especially if combining multiple behaviors).</li><li>When working with <strong>legacy codebases</strong> or APIs that don’t support streams.</li><li>For <strong>type-safe APIs</strong> or libraries where you expose generic behavior.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a87f7695497b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java — Lets learn few features…Resilience]]></title>
            <link>https://medium.com/@dnrvec/java-lets-learn-few-features-resilience-14166aeb0808?source=rss-3c8a25e4419c------2</link>
            <guid isPermaLink="false">https://medium.com/p/14166aeb0808</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[resilience]]></category>
            <dc:creator><![CDATA[Naveen]]></dc:creator>
            <pubDate>Fri, 20 Jun 2025 01:50:40 GMT</pubDate>
            <atom:updated>2025-06-20T01:50:40.992Z</atom:updated>
            <content:encoded><![CDATA[<h3>Java — Lets learn few features…Resilience</h3><p>While there are many features that we can implement, lets start with few resilience annotations</p><blockquote><strong>Retry with </strong><strong>@Retryable (Spring Retry)</strong></blockquote><ul><li>Automatically retries a failed method call.</li><li>Scenarios like retry a flaky payment API up to 3 times before giving up.</li></ul><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;org.springframework.retry&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-retry&lt;/artifactId&gt;<br>&lt;/dependency&gt;<br>&lt;dependency&gt;<br>    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-boot-starter-aop&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><pre>@SpringBootApplication<br>@EnableRetry<br>public class RetryApp {<br>    public static void main(String[] args) {<br>        SpringApplication.run(RetryApp.class, args);<br>    }<br>}<br><br>///////<br>@Service<br>public class PaymentService {<br><br>    @Retryable(<br>        value = { IOException.class },<br>        maxAttempts = 3,<br>        backoff = @Backoff(delay = 2000))<br>    public void callPaymentGateway() throws IOException {<br>        System.out.println(&quot;Calling payment gateway...&quot;);<br>        if (Math.random() &lt; 0.7) throw new IOException(&quot;Temporary network issue&quot;);<br>        System.out.println(&quot;Payment processed successfully&quot;);<br>    }<br><br>    @Recover<br>    public void recover(IOException e) {<br>        System.out.println(&quot;Recovering after retries failed: &quot; + e.getMessage());<br>    }<br>}<br></pre><blockquote><strong>Circuit Breaker with Resilience4j</strong></blockquote><ul><li>Prevents repeated calls to a failing service. Automatically closes after some time.</li><li>Scenarios like stop calling a product service if it fails 3 times in a row.</li></ul><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;io.github.resilience4j&lt;/groupId&gt;<br>    &lt;artifactId&gt;resilience4j-spring-boot3&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><pre>@Service<br>public class ProductService {<br><br>    @CircuitBreaker(name = &quot;productService&quot;, fallbackMethod = &quot;fallback&quot;)<br>    public String getProduct() {<br>        System.out.println(&quot;Calling external product API...&quot;);<br>        if (Math.random() &lt; 0.7) throw new RuntimeException(&quot;Service unavailable&quot;);<br>        return &quot;Product info&quot;;<br>    }<br><br>    public String fallback(Throwable t) {<br>        return &quot;Fallback product info (cached)&quot;;<br>    }<br>}</pre><pre>resilience4j.circuitbreaker:<br>  instances:<br>    productService:<br>      registerHealthIndicator: true<br>      slidingWindowSize: 5<br>      failureRateThreshold: 50<br>      waitDurationInOpenState: 5s</pre><blockquote><strong>Retry vs Circuit Breaker</strong></blockquote><p><strong>Retry — optimistic</strong> — “Let’s keep trying!”</p><ul><li>You expect the failure to be <strong>transient</strong> (e.g., network timeout, temporary rate-limit).</li><li>Retrying increases the chance of success.</li></ul><p><strong>Circuit Breaker — protective</strong> — “Let’s stop before we crash!”</p><ul><li>You want to <strong>stop calling</strong> a service that is <strong>consistently failing</strong>.</li><li>You’re protecting your system from further harm or overload.</li></ul><p><strong>Can You Use Both Together?</strong></p><p>Yes!</p><ul><li><strong>Retry</strong> for quick recovery from transient errors.</li><li><strong>Circuit Breaker</strong> to prevent retrying indefinitely and causing more damage.</li></ul><pre>@Retry(name = &quot;inventoryRetry&quot;)<br>@CircuitBreaker(name = &quot;inventoryCB&quot;, fallbackMethod = &quot;fallback&quot;)<br>public String callInventoryService() {<br>    // External API call<br>}</pre><blockquote><strong>@RateLimiter (Resilience4j)</strong></blockquote><ul><li>Limit how many requests can be served over time (per user, per API, etc.)</li><li>Scenarios like allow max 5 requests per user per minute.</li><li>We can combine redis as well to implement</li></ul><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;com.github.vladimir-bukhtoyarov&lt;/groupId&gt;<br>    &lt;artifactId&gt;bucket4j-core&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><pre>@RestController<br>public class RateLimitedController {<br><br>    private final Bucket bucket;<br><br>    public RateLimitedController() {<br>        Bandwidth limit = Bandwidth.simple(5, Duration.ofMinutes(1));<br>        this.bucket = Bucket4j.builder().addLimit(limit).build();<br>    }<br><br>    @GetMapping(&quot;/api/limited&quot;)<br>    public ResponseEntity&lt;String&gt; call() {<br>        if (bucket.tryConsume(1)) {<br>            return ResponseEntity.ok(&quot;Request processed&quot;);<br>        } else {<br>            return ResponseEntity.status(HttpStatus.TOO_MANY_REQUESTS).body(&quot;Too many requests&quot;);<br>        }<br>    }<br>}<br></pre><blockquote><strong>@Bulkhead (Resilience4j)</strong></blockquote><ul><li>Limits <strong>concurrent calls</strong> to a method (thread isolation).</li><li>Prevents thread exhaustion.</li><li><strong>limit the number of concurrent requests</strong> to a specific part of your system, isolating failures and <strong>preventing cascading failures</strong></li></ul><blockquote><strong>@TimeLimiter (Resilience4j)</strong></blockquote><ul><li>Limits how long a method can take.</li><li>Forces timeout for long-running calls.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=14166aeb0808" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java — Spring Boot Annotations]]></title>
            <link>https://medium.com/@dnrvec/java-spring-boot-annotations-bc64ddca1555?source=rss-3c8a25e4419c------2</link>
            <guid isPermaLink="false">https://medium.com/p/bc64ddca1555</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Naveen]]></dc:creator>
            <pubDate>Tue, 17 Jun 2025 23:05:05 GMT</pubDate>
            <atom:updated>2025-06-17T23:05:05.351Z</atom:updated>
            <content:encoded><![CDATA[<h3>Java — Spring Boot Annotations</h3><p>Listing down majority of spring boot annotations that will be used for quick reference</p><p>Spring Boot uses annotations heavily to simplify configuration and development. Here’s a categorized cheat sheet of <strong>commonly used Spring Boot annotations</strong>, grouped by purpose:</p><blockquote><strong>Core Configuration Annotations</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/986/1*JDdy1rP-cAqQRrKugPUhaw.png" /></figure><blockquote><strong>Component-Level Annotations</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/1*KKULkHl5QtM40JCsJwz3nA.png" /></figure><blockquote><strong>Web &amp; REST Annotations</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/976/1*KX7NvPDoaT-IIP1kN_TAcg.png" /></figure><blockquote><strong>Dependency Injection Annotations</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/1*mqDwOZxVoLQjHw0KZSDQTw.png" /></figure><blockquote><strong>JPA &amp; Persistence Annotations</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/1*T5NypiBW6PCSdMhn_vSnew.png" /></figure><blockquote><strong>Validation Annotations</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*IRXu-J7hTxBsEctiMIGITw.png" /></figure><blockquote><strong>Test Annotations</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/894/1*NDAJcZz_dHIv7B9zcXWVMQ.png" /></figure><h4>Usage Scenarios</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/993/1*QGssm5rZLThQwIreM1k2wQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bc64ddca1555" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Algorithms of machine learning]]></title>
            <link>https://medium.com/@dnrvec/algorithms-of-machine-learning-e64c848b9593?source=rss-3c8a25e4419c------2</link>
            <guid isPermaLink="false">https://medium.com/p/e64c848b9593</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Naveen]]></dc:creator>
            <pubDate>Tue, 17 Jun 2025 23:04:23 GMT</pubDate>
            <atom:updated>2025-06-17T23:04:23.612Z</atom:updated>
            <content:encoded><![CDATA[<p>Grouping different types of algorithms that we come across in this learning cycle</p><h4>1. Logistic Regression</h4><ul><li><strong>Type</strong>: Classification</li><li><strong>Description</strong>: Predicts the probability of a binary outcome using a logistic function.</li><li><strong>Example</strong>: Predict whether an email is spam or not spam.</li></ul><h4>2. k-Nearest Neighbors (k-NN)</h4><ul><li><strong>Type</strong>: Both (Classification &amp; Regression)</li><li><strong>Description</strong>: Predicts the output based on the majority class (classification) or average value (regression) of the nearest k neighbors.</li><li><strong>Example</strong>:</li><li>Classification: Identify if a fruit is an apple, orange, or banana.</li><li>Regression: Predict house price based on nearby similar houses.</li></ul><h4>3. Decision Tree</h4><ul><li><strong>Type</strong>: Both</li><li><strong>Description</strong>: Splits the data into branches based on feature values until it reaches a decision (leaf node).</li><li><strong>Example</strong>:</li><li>Classification: Predict whether a customer will churn.</li><li>Regression: Predict the price of a used car.</li></ul><h4>4. Random Forest</h4><ul><li><strong>Type</strong>: Both</li><li><strong>Description</strong>: An ensemble of decision trees that improves accuracy by averaging (regression) or voting (classification).</li><li><strong>Example</strong>:</li><li>Classification: Detect sentiment in customer reviews.</li><li>Regression: Predict next week’s average temperature.</li></ul><h4>5. Support Vector Machine (SVM)</h4><ul><li><strong>Type</strong>: Both</li><li><strong>Description</strong>: Finds the best hyperplane that separates classes (SVM) or fits the data within a margin (SVR).</li><li><strong>Example</strong>:</li><li>Classification: Identify if an image is a cat or a dog.</li><li>Regression: Predict future stock prices.</li></ul><h4>6. Naive Bayes</h4><ul><li><strong>Type</strong>: Classification</li><li><strong>Description</strong>: A probabilistic model based on Bayes’ theorem assuming feature independence.</li><li><strong>Example</strong>: Classify a document as spam or not spam.</li></ul><h4>7. Multilayer Perceptron (MLP / Neural Network)</h4><ul><li><strong>Type</strong>: Both</li><li><strong>Description</strong>: A deep learning model with layers of neurons; uses softmax for classification and linear output for regression.</li><li><strong>Example</strong>:</li><li>Classification: Handwritten digit recognition (0–9).</li><li>Regression: Predict house prices.</li></ul><h4>8. Linear Discriminant Analysis (LDA)</h4><ul><li><strong>Type</strong>: Classification</li><li><strong>Description</strong>: Projects data to maximize separation between multiple classes.</li><li><strong>Example</strong>: Classify patients into disease risk categories.</li></ul><h4>9. k-Means Clustering</h4><ul><li><strong>Type</strong>: Unsupervised Clustering</li><li><strong>Description</strong>: Groups data into k clusters based on feature similarity.</li><li><strong>Example</strong>: Segment customers into groups based on shopping habits.</li></ul><h4>10. Linear Regression</h4><ul><li><strong>Type</strong>: Regression</li><li><strong>Description</strong>: Fits a straight line through data to predict continuous values.</li><li><strong>Example</strong>: Predict the selling price of a house based on its size.</li></ul><h4>11. Ridge Regression</h4><ul><li><strong>Type</strong>: Regression</li><li><strong>Description</strong>: Linear regression with L2 regularization to reduce overfitting.</li><li><strong>Example</strong>: Predict house price while keeping model coefficients small.</li></ul><h4>12. Lasso Regression</h4><ul><li><strong>Type</strong>: Regression</li><li><strong>Description</strong>: Linear regression with L1 regularization that can shrink some coefficients to zero (feature selection).</li><li><strong>Example</strong>: Predict salary based on many job-related features, automatically ignoring less important ones.</li></ul><h4>13. Support Vector Regression (SVR)</h4><ul><li><strong>Type</strong>: Regression</li><li><strong>Description</strong>: Uses the same principles as SVM but fits a function within a margin to predict continuous values.</li><li><strong>Example</strong>: Predict next month’s stock prices based on recent trends.</li></ul><h3>🔶 Unsupervised Learning Algorithms</h3><p>These algorithms <strong>do not use labeled data</strong>. The model finds patterns, groupings, or structures in the data on its own.</p><h4>1. k-Means Clustering</h4><ul><li><strong>Type</strong>: Clustering (Unsupervised)</li><li><strong>Description</strong>: Partitions data into <em>k</em> clusters based on feature similarity; each point belongs to the nearest cluster center.</li><li><strong>Example</strong>: Group retail customers based on purchase behavior into segments like “bargain hunters,” “loyal customers,” etc.</li></ul><h4>2. Hierarchical Clustering</h4><ul><li><strong>Type</strong>: Clustering (Unsupervised)</li><li><strong>Description</strong>: Builds a hierarchy (tree-like structure) of clusters by either merging or splitting groups.</li><li><strong>Example</strong>: Organize animals by genetic similarity or group documents by topic.</li></ul><h4>3. DBSCAN (Density-Based Spatial Clustering)</h4><ul><li><strong>Type</strong>: Clustering (Unsupervised)</li><li><strong>Description</strong>: Finds clusters of arbitrary shape based on density. It identifies noise and outliers.</li><li><strong>Example</strong>: Detect geographic clusters of earthquakes or unusual behavior in a network.</li></ul><h4>4. Principal Component Analysis (PCA)</h4><ul><li><strong>Type</strong>: Dimensionality Reduction (Unsupervised)</li><li><strong>Description</strong>: Reduces high-dimensional data to fewer components while retaining most variance.</li><li><strong>Example</strong>: Compress image data or simplify genetic data before analysis.</li></ul><h4>5. Autoencoders</h4><ul><li><strong>Type</strong>: Dimensionality Reduction / Feature Learning (Unsupervised)</li><li><strong>Description</strong>: Neural networks that learn compressed representations (encoding) and attempt to reconstruct the input.</li><li><strong>Example</strong>: Reduce image noise or extract compressed features for image search.</li></ul><h3>🔷 Ensemble Learning Algorithms</h3><p>These combine multiple models to improve prediction performance, reduce variance, and avoid overfitting.</p><h4>6. Random Forest</h4><ul><li><strong>Type</strong>: Both Classification and Regression</li><li><strong>Description</strong>: Combines multiple decision trees trained on different subsets of the data and features.</li><li><strong>Example</strong>:</li><li>Classification: Predict if a review is positive or negative.</li><li>Regression: Predict energy consumption of a building.</li></ul><h4>7. Gradient Boosting Machines (GBM)</h4><ul><li><strong>Type</strong>: Both</li><li><strong>Description</strong>: Builds models sequentially where each new model corrects the errors of the previous ones.</li><li><strong>Example</strong>: Predict likelihood of loan default based on customer history.</li></ul><h4>8. XGBoost / LightGBM / CatBoost</h4><ul><li><strong>Type</strong>: Both</li><li><strong>Description</strong>: Highly optimized versions of gradient boosting with better speed and regularization.</li><li><strong>Example</strong>: Predict click-through rate on online ads or customer churn.</li></ul><h4>9. Voting Classifier / Averaging Regressor</h4><ul><li><strong>Type</strong>: Both</li><li><strong>Description</strong>: Combines predictions from multiple models by voting (classification) or averaging (regression).</li><li><strong>Example</strong>: Use SVM, k-NN, and Random Forest together to classify a medical diagnosis more accurately.</li></ul><h3>🔵 Deep Learning Architectures</h3><p>Deep learning is a subset of machine learning that uses <strong>neural networks with many layers</strong>.</p><h4>10. Convolutional Neural Networks (CNNs)</h4><ul><li><strong>Type</strong>: Classification / Detection (Supervised)</li><li><strong>Description</strong>: Specialized for processing grid-like data such as images. Extract spatial features using filters.</li><li><strong>Example</strong>: Classify handwritten digits (MNIST) or detect objects in images (cats, cars, etc.).</li></ul><h4>11. Recurrent Neural Networks (RNNs) / LSTMs</h4><ul><li><strong>Type</strong>: Sequence Modeling (Supervised)</li><li><strong>Description</strong>: Designed for sequential data. LSTMs solve long-term dependency issues.</li><li><strong>Example</strong>: Predict next word in a sentence or forecast time-series data like weather or sales.</li></ul><h4>12. Transformers</h4><ul><li><strong>Type</strong>: Sequence Modeling (Supervised, Self-Supervised)</li><li><strong>Description</strong>: Use attention mechanisms to model long-range dependencies in sequences, very efficient for NLP.</li><li><strong>Example</strong>: Language translation, text summarization, ChatGPT itself!</li></ul><h4>13. GANs (Generative Adversarial Networks)</h4><ul><li><strong>Type</strong>: Generative (Unsupervised/Self-Supervised)</li><li><strong>Description</strong>: Two networks (Generator + Discriminator) compete to produce realistic data.</li><li><strong>Example</strong>: Generate synthetic faces, art, or deepfake videos.</li></ul><h4>14. Self-Organizing Maps (SOMs)</h4><ul><li><strong>Type</strong>: Clustering / Dimensionality Reduction (Unsupervised)</li><li><strong>Description</strong>: A neural network that maps high-dimensional input to a lower-dimensional space for visualization.</li><li><strong>Example</strong>: Visualize customer similarity or image features.</li></ul><h3>✅ Summary</h3><ul><li><strong>Unsupervised</strong>: No labels → find patterns, clusters, or reduce dimensions.</li><li><strong>Ensemble</strong>: Combine multiple models → better accuracy, robustness.</li><li><strong>Deep Learning</strong>: Neural networks → handle images, text, sequences, generation tasks.</li></ul><p>Now, let’s walk through <strong>one scenario</strong> and see how <strong>each algorithm</strong> would apply.</p><h3>🎯 Scenario: You work at a healthcare startup building a system to help hospitals and doctors predict and manage patient health outcomes.</h3><h3>🔵 Classification Algorithms</h3><h4>1. Logistic Regression</h4><ul><li><strong>Use</strong>: Predict if a patient will develop diabetes (yes/no).</li><li><strong>Why</strong>: Simple, fast, good baseline for binary outcomes.</li></ul><h4>2. k-NN</h4><ul><li><strong>Use</strong>: Classify a patient’s condition based on similar historical patients (diabetic or not).</li><li><strong>Why</strong>: Easy to implement, works well with small datasets.</li></ul><h4>3. Decision Tree</h4><ul><li><strong>Use</strong>: Decide if a patient needs urgent care based on symptoms.</li><li><strong>Why</strong>: Interpretable and follows human-like reasoning.</li></ul><h4>4. Random Forest</h4><ul><li><strong>Use</strong>: Predict disease type using multiple patient features.</li><li><strong>Why</strong>: Reduces overfitting, improves accuracy.</li></ul><h4>5. SVM</h4><ul><li><strong>Use</strong>: Classify patient MRI images as normal vs abnormal.</li><li><strong>Why</strong>: Effective with high-dimensional medical imaging data.</li></ul><h4>6. Naive Bayes</h4><ul><li><strong>Use</strong>: Classify whether a patient report is a high-risk or low-risk alert.</li><li><strong>Why</strong>: Fast and effective with text-based data.</li></ul><h4>7. MLP (Neural Network)</h4><ul><li><strong>Use</strong>: Classify X-ray scans into disease categories.</li><li><strong>Why</strong>: Learns complex non-linear patterns.</li></ul><h4>8. LDA</h4><ul><li><strong>Use</strong>: Reduce features and classify patient risk levels.</li><li><strong>Why</strong>: Good for dimensionality reduction + classification.</li></ul><h3>🟢 Regression Algorithms</h3><h4>9. Linear Regression</h4><ul><li><strong>Use</strong>: Predict the cost of a patient’s treatment.</li><li><strong>Why</strong>: Simple, interpretable baseline.</li></ul><h4>10. Ridge Regression</h4><ul><li><strong>Use</strong>: Predict treatment cost while preventing overfitting.</li><li><strong>Why</strong>: Handles multicollinearity well.</li></ul><h4>11. Lasso Regression</h4><ul><li><strong>Use</strong>: Predict cost and eliminate irrelevant patient features.</li><li><strong>Why</strong>: Performs feature selection.</li></ul><h4>12. SVR (Support Vector Regression)</h4><ul><li><strong>Use</strong>: Predict the length of hospital stay.</li><li><strong>Why</strong>: Handles non-linear relationships with kernel tricks.</li></ul><h4>13. k-NN Regression</h4><ul><li><strong>Use</strong>: Predict a patient’s recovery time based on similar cases.</li><li><strong>Why</strong>: Good when similar examples produce similar outcomes.</li></ul><h4>14. Decision Tree Regressor</h4><ul><li><strong>Use</strong>: Predict the time until next doctor visit.</li><li><strong>Why</strong>: Handles non-linear and interaction terms.</li></ul><h4>15. Random Forest Regressor</h4><ul><li><strong>Use</strong>: Predict future patient expenses.</li><li><strong>Why</strong>: Robust and handles large feature sets.</li></ul><h4>16. MLP for Regression</h4><ul><li><strong>Use</strong>: Predict future blood pressure levels.</li><li><strong>Why</strong>: Can capture complex time trends if fed past data.</li></ul><h3>🟣 Unsupervised Learning</h3><h4>17. k-Means</h4><ul><li><strong>Use</strong>: Segment patients by lifestyle patterns.</li><li><strong>Why</strong>: Simple and effective for grouping.</li></ul><h4>18. Hierarchical Clustering</h4><ul><li><strong>Use</strong>: Understand relationships between genetic conditions.</li><li><strong>Why</strong>: Builds a visual hierarchy of similarity.</li></ul><h4>19. DBSCAN</h4><ul><li><strong>Use</strong>: Detect unusual patient behavior (anomalies).</li><li><strong>Why</strong>: Finds outliers, doesn’t need pre-defined clusters.</li></ul><h4>20. PCA</h4><ul><li><strong>Use</strong>: Reduce dimensionality of lab test data.</li><li><strong>Why</strong>: Helps visualize and simplify data.</li></ul><h4>21. Autoencoders</h4><ul><li><strong>Use</strong>: Compress patient data for anomaly detection.</li><li><strong>Why</strong>: Learns efficient representations.</li></ul><h4>22. Self-Organizing Maps (SOMs)</h4><ul><li><strong>Use</strong>: Visualize patient health profiles in 2D.</li><li><strong>Why</strong>: Great for interpreting high-dimensional data.</li></ul><h3>🔶 Deep Learning Architectures</h3><h4>23. CNN (Convolutional Neural Network)</h4><ul><li><strong>Use</strong>: Detect pneumonia from chest X-rays.</li><li><strong>Why</strong>: Best for spatial image data.</li></ul><h4>24. RNN / LSTM</h4><ul><li><strong>Use</strong>: Predict patient heart rate over time.</li><li><strong>Why</strong>: Designed for sequential, time-series data.</li></ul><h4>25. Transformers</h4><ul><li><strong>Use</strong>: Analyze patient-doctor chat transcripts.</li><li><strong>Why</strong>: Handles long text sequences efficiently.</li></ul><h4>26. GANs</h4><ul><li><strong>Use</strong>: Generate synthetic medical images for training.</li><li><strong>Why</strong>: Useful for data augmentation.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e64c848b9593" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java — Streams and usage]]></title>
            <link>https://medium.com/@dnrvec/java-streams-and-usage-a353b8824f44?source=rss-3c8a25e4419c------2</link>
            <guid isPermaLink="false">https://medium.com/p/a353b8824f44</guid>
            <category><![CDATA[javastreams]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Naveen]]></dc:creator>
            <pubDate>Tue, 17 Jun 2025 22:04:20 GMT</pubDate>
            <atom:updated>2025-06-17T22:04:20.446Z</atom:updated>
            <content:encoded><![CDATA[<h3>Java — Streams and usage</h3><h4>What is a Java Stream?</h4><ul><li>A <strong>stream</strong> is a sequence of elements supporting <strong>sequential and parallel</strong> operations.</li><li>It <strong>doesn’t store data</strong>, but rather <strong>processes data</strong> from a source (like List, Set, or arrays).</li></ul><h4>Stream Pipeline Structure</h4><p>A typical stream pipeline has <strong>3 components</strong>:</p><ol><li><strong>Source</strong> (e.g., list.stream())</li><li><strong>Intermediate Operations</strong> (e.g., filter, map)</li><li><strong>Terminal Operation</strong> (e.g., collect, forEach)</li></ol><pre>List&lt;String&gt; result = names.stream()<br>                           .filter(name -&gt; name.startsWith(&quot;A&quot;))<br>                           .map(String::toUpperCase)<br>                           .sorted()<br>                           .collect(Collectors.toList());</pre><h4>Common Stream Functions (Internal APIs)</h4><p><em>🔹 1. </em><em>filter(Predicate)-Filters elements based on a boolean condition.</em></p><pre>list.stream().filter(x -&gt; x &gt; 5)</pre><p><em>🔹 2. </em><em>map(Function)- Transforms each element.</em></p><pre>names.stream().map(String::toUpperCase)</pre><p><em>🔹 3. </em><em>flatMap(Function)- Flattens nested structures.</em></p><pre>listOfLists.stream().flatMap(List::stream)</pre><p><em>🔹 4. </em><em>distinct()- Removes duplicates.</em></p><pre>list.stream().distinct()</pre><p><em>🔹 5. </em><em>sorted(), </em><em>sorted(Comparator)- Sorts the stream.</em></p><pre>list.stream().sorted()<br>list.stream().sorted(Comparator.reverseOrder())</pre><p><em>🔹 6. </em><em>limit(n) / </em><em>skip(n)- Limit or skip elements in a stream.</em></p><pre>list.stream().limit(5)<br>list.stream().skip(2)</pre><p><em>🔹 7. </em><em>peek(Consumer)- Useful for debugging — lets you “peek” at the elements without modifying.</em></p><pre>list.stream()<br>    .peek(System.out::println)<br>    .filter(x -&gt; x &gt; 10)</pre><p><em>🔹 8. </em><em>collect(...) (Terminal)- Gather the result into a collection or a value.</em></p><pre>list.stream().collect(Collectors.toList())<br>list.stream().collect(Collectors.joining(&quot;, &quot;))<br>list.stream().collect(Collectors.groupingBy(String::length))</pre><p><em>🔹 9. </em><em>forEach(...) (Terminal)- Apply an action to each element (doesn’t return a result).</em></p><pre>list.stream().forEach(System.out::println)</pre><p><em>🔹 10. </em><em>reduce(...) (Terminal)- Combine elements into a single result.</em></p><pre>int sum = list.stream().reduce(0, Integer::sum);</pre><p><em>🔹 11. </em><em>anyMatch, </em><em>allMatch, </em><em>noneMatch- Match predicates against stream content.</em></p><pre>list.stream().anyMatch(x -&gt; x &gt; 10)<br>list.stream().allMatch(x -&gt; x != null)</pre><p><em>🔹 12. </em><em>findFirst, </em><em>findAny- Retrieve elements from a stream.</em></p><pre>list.stream().findFirst()<br>list.parallelStream().findAny()</pre><p><em>🔹 13. </em><em>parallelStream()- Run the stream </em><strong><em>in parallel</em></strong><em> for better performance (in some cases).</em></p><pre>list.parallelStream()</pre><pre>List&lt;Order&gt; recentOrders = orders.stream()<br>    .filter(o -&gt; o.getDate().isAfter(LocalDate.now().minusDays(30)))<br>    .filter(o -&gt; o.getAmount() &gt; 100)<br>    .sorted(Comparator.comparing(Order::getDate).reversed())<br>    .collect(Collectors.toList());</pre><h4>Real-World Use Case: Order Processing with Streams</h4><p>Imagine we have a list of Order objects and we want to:</p><ul><li>Filter orders from the last 7 days</li><li>Only include orders above $100</li><li>Sort by amount descending</li><li>Collect order IDs into a list</li></ul><pre>List&lt;Order&gt; recentLargeOrderIds = orders.stream()<br>    .filter(o -&gt; o.getDate().isAfter(LocalDate.now().minusDays(7)))<br>    .filter(o -&gt; o.getAmount() &gt; 100)<br>    .sorted(Comparator.comparing(Order::getAmount).reversed())<br>    .map(Order::getId)<br>    .collect(Collectors.toList());</pre><h4><strong>map() vs flatMap()</strong></h4><p>map() Returns a <strong>Stream of Stream</strong> (or nested structure)</p><p>flatMap() Returns a <strong>flattened Stream</strong> (no nesting)</p><pre>class Category {<br>    String name;<br>    List&lt;Product&gt; products;<br>}<br><br>class Product {<br>    String name;<br>}</pre><pre><br>// With map, You still need to unwrap the inner list manually if you want a flat list of all products<br>List&lt;Category&gt; categories = ...;<br><br>Stream&lt;List&lt;Product&gt;&gt; productLists = categories.stream()<br>    .map(Category::getProducts);<br><br>// With flatmap, All products from all categories are flattened into a single stream.<br><br>Stream&lt;Product&gt; allProducts = categories.stream()<br>    .flatMap(category -&gt; category.getProducts().stream());<br><br></pre><h4>filter() vs map()</h4><p>filter() Selects elements based on a condition. Reduces the number of elements</p><p>map() Transforms each element to another form. Keeps the number the same (usually)</p><pre>list.stream().filter(n -&gt; n &gt; 10)   // keeps only values &gt; 10<br>list.stream().map(n -&gt; n * 2)       // multiplies every value by 2</pre><h4>collect() vs forEach()</h4><p>collect() Terminal operation, returns result. Used to gather results into a collection</p><p>forEach() Terminal operation, returns void . Used for side effects (like printing) Functional More imperative</p><pre>List&lt;String&gt; names = people.stream()<br>    .map(Person::getName)<br>    .collect(Collectors.toList());<br><br>people.stream().forEach(System.out::println);</pre><h4>reduce() vs collect()</h4><p>reduce() Reduces stream to a single value. Best for aggregation (sum, product)</p><p>collect() Accumulates elements into a collection. Best for building collections</p><pre>int sum = numbers.stream().reduce(0, Integer::sum); // reduces to single int<br><br>List&lt;Integer&gt; evenNumbers = numbers.stream()<br>    .filter(n -&gt; n % 2 == 0)<br>    .collect(Collectors.toList()); // collects to list</pre><h4>Best Practices</h4><ul><li><strong>Avoid mutating state</strong> inside streams.</li><li>Prefer <strong>method references</strong> (map(String::toUpperCase)).</li><li>Use <strong>parallel streams</strong> cautiously — only for CPU-heavy, independent operations.</li><li>Use collect(Collectors.toMap()), groupingBy(), and partitioningBy() for powerful aggregations.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a353b8824f44" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>