🧩⚡ COLLECTORS.TEEING(): TWO AGGREGATIONS, ONE STREAM PASS 🔸 TLDR ▪️ Need two aggregations? teeing() does it in one collect with a clean immutable merge. 🔸 THE PROBLEM Ever needed two aggregations (ex: count + sum) on the same stream? The “classic” approach often streams the data twice — simple, but not always ideal. 🔸 CODE: OLD VS MODERN // ✕ Java 8: two passes long count = items.stream().count(); double sum = items.stream() .mapToDouble(Item::price) .sum(); var result = new Stats(count, sum); // ✓ Java 12+: one pass with teeing() var result = items.stream().collect( Collectors.teeing( Collectors.counting(), Collectors.summingDouble(Item::price), Stats::new ) ); 🔸 SEE A PROBLEM WITH THIS CODE? LET US KNOW 👀 Hint: there’s a subtle one depending on what items is… 😉 🔸 WHY THE MODERN WAY WINS ▪️ ⚡ Single pass: stream once, aggregate twice ▪️ 🧩 Composable: mix any 2 collectors (min/max, summary stats, grouping, etc.) ▪️ 🔒 Immutable result: merge straight into a record / value object 🔸 HOW IT WORKS (IN 1 SENTENCE) Collectors.teeing() routes each element to two downstream collectors, then merges both results using your merger function (Stats::new here). 🔸 TAKEAWAYS ▪️ Prefer teeing() when you want two results from one stream without mutable accumulators ▪️ Great fit for Stats/DTO/record building ▪️ Still keep readability in mind: for tiny lists, two passes can be totally fine ✅ #Java #Java12 #Streams #Collectors #FunctionalProgramming #CleanCode #Performance #BackendDevelopment #JVM src: https://lnkd.in/ezn22fFC Go further with Java certification: Java👇 https://lnkd.in/eZKYX5hP Spring👇 https://lnkd.in/eADWYpfx SpringBook👇 https://bit.ly/springtify JavaBook👇 https://bit.ly/jroadmap
Vincent Vauban’s Post
More Relevant Posts
-
New to Spring Boot? You'll see these annotations in every project. Here's what they actually do: @SpringBootApplication → Entry point. Combines @Configuration, @EnableAutoConfiguration, @ComponentScan @RestController → Marks a class as an HTTP request handler that returns data (not views) @Service → Business logic layer. Spring manages it as a bean @Repository → Data access layer. Also enables Spring's exception translation @Autowired → Inject a dependency automatically (prefer constructor injection instead) @GetMapping / @PostMapping / @PutMapping / @DeleteMapping → Maps HTTP methods to your handler methods @RequestBody → Deserializes JSON from request body into a Java object @PathVariable → Extracts values from the URL path Bookmark this. You'll refer back to it constantly. Which annotation confused you the most when starting out? 👇 #Java #SpringBoot #Annotations #BackendDevelopment #LearningInPublic
To view or add a comment, sign in
-
🚨 A Small File That Caused a Big Headache: classpath.txt Recently, I ran into an issue while working on a large Java project built with Maven. I was trying to start the application using an external dependency — the H2 database driver. Everything seemed correct. I followed the existing instructions carefully. I even executed a bash command to copy the H2 driver into the classes folder. But then… 💥 Error: Class not found (H2 driver) I got stuck. 🤔 What was missing? After digging around, I realized something important: 👉 The H2 driver was not declared in classpath.txt And surprisingly… this step wasn’t mentioned in the documentation. 📌 So, what is classpath.txt? In simple terms: 👉 classpath.txt is a file that tells Java where to find your classes and external libraries when the application runs. Think of it like a “map” 📍 If a library (like H2) is not listed there, Java simply cannot see it, even if the file physically exists in your project. ⚠️ Why copying files isn’t enough I assumed that copying the .jar into the classes folder would be enough. But Java doesn’t automatically scan everything in that folder. 👉 If it’s not in the classpath → it doesn’t exist (from Java’s perspective) ✅ The fix Once I added the H2 driver path into classpath.txt, everything worked immediately. 💡 Key takeaways If you import an external library without declaring it in pom.xml, make sure it is also added to classpath.txt so the compiler and runtime can detect it If you declare dependencies properly in pom.xml, Maven will handle the classpath for you — no need to manually add them to classpath.txt When you see a “Class not found” error, always double-check how your dependencies are being included 🚀 What I learned This bug helped me truly understand: How Java loads dependencies at runtime The role of classpath.txt in builds The right way to include external libraries Sometimes, the smallest files teach the biggest lessons. If you’ve ever been stuck on a “Class not found” error, you know the pain 😅 Hope this saves someone a few hours (or days). #Java #Maven #Debugging #SoftwareEngineering #Learning
To view or add a comment, sign in
-
Hi everyone 👋 Continuing the Spring Boot Annotation Series 👇 📌 Spring Boot Annotation Series part 24 – @ResponseBody @ResponseBody is used to return data directly in the HTTP response body instead of returning a view (HTML page). It is part of the Spring Framework and is commonly used in REST APIs built with Spring Boot. 🔹 Why do we use @ResponseBody? In Spring MVC: Without @ResponseBody → returns a view (HTML/JSP) With @ResponseBody → returns data (JSON/XML) 👉 It is mainly used for building REST APIs. 🔹 Simple Example @Controller public class UserController { @GetMapping("/user") @ResponseBody public String getUser() { return "User details"; } } 👉 Output will be directly shown in response body, not a view. 🔹 Returning Object as JSON @GetMapping("/user") @ResponseBody public User getUser() { return new User(1, "Asmita"); } 👉 Spring automatically converts it into JSON. 🔹 How does it work? - Spring uses Jackson library internally - Converts Java object → JSON - Sends it in HTTP response 🔹 In Simple Words @ResponseBody tells Spring to send data directly in the response instead of returning a web page. 👉 🧠 Quick Understanding - Returns data, not view - Converts object → JSON - Used in REST APIs - Not needed with @RestController #SpringBoot #Java #ResponseBody #RESTAPI #BackendDevelopment #LearningInPublic
To view or add a comment, sign in
-
Hi everyone 👋 📌 Spring Boot Annotation Series Part 22– @RequestParam @RequestParam is used to read query parameters from the request URL and bind them to method parameters. It is part of the Spring Framework and commonly used in REST APIs built with Spring Boot. 🔹 Why do we use @RequestParam? Sometimes we need to pass additional information through the URL. Example: GET /users?age=25 Here, age is a query parameter. @RequestParam helps us capture that value in the controller method. 🔹 Simple Example @RestController @RequestMapping("/users") public class UserController { @GetMapping("/search") public String getUserByAge(@RequestParam int age) { return "User age is: " + age; } } 👉 Request URL: GET http://localhost:8080/users/search?age=25 Output: User age is: 25 🔹 In Simple Words @RequestParam takes values from query parameters in the URL and passes them to the controller method. 👉 🧠 Quick Understanding Used in filtering, search APIs Can be optional using required=false Can provide default values Used to read query parameters from URL Mostly used in GET APIs #SpringBoot #Java #RESTAPI #RequestParam #BackendDevelopment #LearningInPublic
To view or add a comment, sign in
-
#Post2 In the previous post, we understood what a REST API is. Now the next question is 👇 How do we actually build REST APIs in Spring Boot? That’s where @RestController comes in 🔥 @RestController is a special annotation used to create REST APIs. It combines two things: • @Controller • @ResponseBody 👉 Meaning: Whatever method returns → it is written directly to the HTTP response body (usually JSON for objects) Example: @RestController public class UserController { @GetMapping("/user") public String getUser() { return "Hello User"; } } Output → "Hello User" (sent as response) 💡 Key difference: @Controller → used for returning views (JSP/HTML) @RestController → used for REST APIs (JSON response) Key takeaway: If you are building APIs in Spring Boot → @RestController is your starting point 🚀 In the next post, we will understand how request mapping works using @GetMapping and others 🔥 #Java #SpringBoot #BackendDevelopment #RESTAPI #LearnInPublic
To view or add a comment, sign in
-
#Post5 So far in this series, we explored concepts like HashMap, ConcurrentHashMap, CAS, and volatile. Now let’s step back and understand the foundation. We will now start with Multithreading Fundamentals. How does our code actually run? What is a Process and Thread? From Code to Process When we write a Java program: Compilation: javac Test.java → generates bytecode Execution: java Test → starts the program At this point, the JVM starts a new process in the operating system. This process is responsible for executing our program. The OS allocates resources to this process such as: • Memory • CPU time • Threads What is a Process? A process is simply a running instance of a program. Each process has its own memory and resources allocated by the operating system. What is a Thread? A thread is the smallest unit of execution inside a process. When a process starts, it begins with one thread called the main thread. From there, we can create multiple threads to perform tasks concurrently. Multitasking vs Multithreading Multitasking: The operating system runs multiple processes at the same time. Multithreading: A single process runs multiple threads concurrently. In simple terms: Operating System → Multiple Processes (Multitasking) → Each Process contains multiple Threads (Multithreading) Example Think of a web application: • One thread handles user requests • Another thread processes data • Another thread sends responses This allows multiple tasks to run efficiently at the same time. Key takeaway Code execution flow: Code → JVM → Process → Threads Understanding this flow is important because all advanced concepts like synchronization, CAS, and concurrent data structures are built on top of threads. In the next post, we’ll explore what happens inside a process (heap, stack, memory structure). #Java #SoftwareEngineering #Multithreading #BackendDevelopment #Programming
To view or add a comment, sign in
-
🚀 Spring Annotation-Based Configuration (Beginner Friendly Guide) If you’re starting with Spring, understanding how the IOC container works is super important. Let’s break it down with a simple example 👇 👉 1. Main Class (Entry Point) import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Main { public static void main(String[] args) { // Step 1: Load Spring configuration file ApplicationContext container = new ClassPathXmlApplicationContext("applicationContext.xml"); // Step 2: IOC container is ready and beans are created automatically System.out.println("IOC Container Loaded Successfully ✅"); } } 👉 2. applicationContext.xml (Configuration File) <beans xmlns="https://lnkd.in/d858D-Nk" xmlns:xsi="https://lnkd.in/dNJZbNmc" xmlns:context="https://lnkd.in/dEDWzfEq" xsi:schemaLocation=" https://lnkd.in/d858D-Nk https://lnkd.in/dbit7sVK https://lnkd.in/dEDWzfEq https://lnkd.in/daN7U-FT"> <!-- Scan this package for annotations --> <context:component-scan base-package="org.annotationbasedconfiguration"/> </beans> 💡 What does this mean? ✔️ Spring reads the XML file ✔️ Scans the given package ✔️ Finds classes with annotations like: @Component @Service @Repository ✔️ Automatically creates objects (Beans) and manages them 🎯 Why use an Annotation-Based Approach? ✅ Less XML configuration ✅ Cleaner code ✅ Easy to manage ✅ Industry standard approach 👉 Simple Understanding: "Just add annotations in your class, and Spring will create & manage objects for you." #Java #SpringFramework #Beginners #BackendDevelopment #IoC #DependencyInjection #CodingJourney
To view or add a comment, sign in
-
🚀 Going Deeper into Backend Development with Spring Boot Today’s focus was not just writing APIs, but understanding how a real backend project should be structured. I explored how to organize a Spring Boot application using a proper package structure: • Controller – Handles incoming HTTP requests • Service – Contains business logic • Repository – Handles database interaction Along with this, I started learning the core concepts behind database interaction in Java applications: • ORM (Object Relational Mapping) • JPA (Java Persistence API) • Spring Data JPA Understanding these concepts helped me see how Java objects can be mapped to database tables and how Spring simplifies database operations. Small step, but an important one in building clean and maintainable backend systems. #SpringBoot #BackendDevelopment #Java #SoftwareEngineering #LearningJourney
To view or add a comment, sign in
-
-
Last week I moved from Spring theory to hands-on implementation and explored how the Spring Framework works internally using XML configuration. After learning about IoC (Inversion of Control) and Dependency Injection, I built multiple small examples to understand how the Spring Container (BeanFactory / ApplicationContext) manages objects and dependencies. Concepts I implemented: 🔹 Spring IoC Container 🔹 Dependency Injection (DI) 🔹 XML-based Bean Configuration 🔹 Setter Injection & Constructor Injection 🔹 "ref" attribute for bean referencing 🔹 Autowiring ("@Autowired" and XML autowire modes) 🔹 Bean Scope (Singleton / Prototype) 🔹 Inner Beans 🔹 Lazy Initialization ("lazy-init") 🔹 Different ways of Object Creation in Spring Working through these examples helped me better understand how Spring manages bean creation, dependency resolution, and the bean lifecycle behind the scenes — which forms the foundation of modern Spring Boot applications. 📂 GitHub Repository: https://lnkd.in/dcJMpUKJ Continuing to explore deeper into the Spring ecosystem and backend development with Java. #SpringFramework #SpringBoot #Java #BackendDevelopment #IoC #DependencyInjection #LearningInPublic
To view or add a comment, sign in
More from this author
Explore related topics
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development