📌 Collectors in Java Streams — Transforming Data Efficiently Collectors are used with streams to transform and gather results into collections or other structures. They are mainly used with: collect() — a terminal operation --- 1️⃣ What is collect()? collect() converts a stream into a final result like: • List • Set • Map • Grouped data Example: List<Integer> list = stream.collect(Collectors.toList()); --- 2️⃣ Common Collectors 🔹 toList() Convert stream to List list.stream() .collect(Collectors.toList()); --- 🔹 toSet() Removes duplicates list.stream() .collect(Collectors.toSet()); --- 🔹 toMap() Convert to Map list.stream() .collect(Collectors.toMap( key -> key.getId(), value -> value )); --- 3️⃣ groupingBy (Very Important) Groups elements based on a key Example: Map<String, List<Employee>> map = employees.stream() .collect(Collectors.groupingBy( e -> e.getDepartment() )); --- 4️⃣ counting() Counts elements long count = list.stream() .collect(Collectors.counting()); --- 5️⃣ joining() Joins strings String result = list.stream() .collect(Collectors.joining(", ")); --- 6️⃣ Why Collectors Are Powerful ✔ Transform data easily ✔ Replace complex loops ✔ Enable grouping and aggregation ✔ Improve readability --- 🧠 Key Takeaway Collectors turn streams into meaningful results. They are essential for data transformation and aggregation. #Java #Java8 #Streams #Collectors #BackendDevelopment
Java Streams Collectors: Transforming Data with Efficiency
More Relevant Posts
-
One trace. 572,789 spans. 62% of all trace data in a five-minute sample, from a single service. This was a batch processing job. The #OpenTelemetry Java auto-instrumentation agent created a span for every database call inside a loop. The agent does not have a built-in span count cap per trace. It instruments what it finds, and a batch job iterating over hundreds of thousands of records will produce hundreds of thousands of spans. The trace was unusable. No backend renders half a million spans in a waterfall view. The cost was astronomical, and the four largest traces in the sample had no root span metadata, suggesting missing or disconnected parent spans. Most originated from batch or scheduled tasks like `https://lnkd.in/dBWthabm`. This organization runs 3,532 services, all on Java auto-instrumentation v1.33.6. The agent works well for request-response services. It was never designed for uncapped iteration over data. The fix depends on the batch pattern. For jobs that process items independently, use span links instead of parent-child relationships. Each item gets its own trace, linked back to the batch trace. This keeps individual traces small and queryable while preserving the connection to the batch context. For specific instrumentation that generates noise, the agent supports suppression flags. Setting `otel.instrumentation.common.experimental.suppress-messaging-receive-spans=true` eliminates receive spans for messaging consumers. Similar flags exist for JDBC, Redis, and other libraries. Review which instrumentations fire inside your loops and suppress the ones that add volume without insight. Auto-instrumentation assumes your services handle requests. When your workload does not fit that model, you need guardrails. The agent will not set them for you. And about last Friday's quiz: what does `stability: stable` mean for an OpenTelemetry semantic convention attribute? The answer is that it follows semver deprecation rules. A stable attribute is not frozen. It can still be deprecated, but the project must provide a migration path and maintain backward compatibility for a defined period. An `experimental` attribute carries no such guarantee and might be renamed or removed between releases. If you build dashboards or code generation around an experimental attribute, you accept the risk of breakage on upgrade.
To view or add a comment, sign in
-
Stop treating Java Collections like simple "buckets." 🪣 Most developers stop at ArrayList and HashMap. But in 2026, the real power lies in using Collections as intelligent data pipelines, not just storage. I just published a deep dive into some "non-standard" ways to level up your Java architecture: 🔹 Type-Safe Heterogeneous Containers: How to bypass type erasure and build flexible, type-safe registries without the instanceof mess. 🔹 Sequenced Collections: Why Java 21+ finally fixed the "last element" headache and how it changes breadcrumb logic. 🔹 Custom Business Collectors: Moving your logic out of the service layer and into the stream for cleaner, more functional code. 🔹 The BitSet Comeback: Why bit-level optimization is the secret weapon for reducing cloud memory costs. The "Java way" has evolved. It’s no longer about verbosity—it’s about intent. Check out the full breakdown on Medium: https://lnkd.in/eKvu4PDX Are you still using standard Collections, or have you started implementing these advanced patterns? Let’s talk in the comments. 👇 #Java #SoftwareEngineering #CleanCode #Backend #ProgrammingTips #MediumWriter
To view or add a comment, sign in
-
🚀 Day 21 – Records in Java: The Modern Way to Model Data Java Records are a powerful feature introduced to simplify how we represent immutable data. No boilerplate. No ceremony. Just clean, minimal, and intention-driven code. Here’s what makes Records a game-changer: 🔹 1. Zero Boilerplate No need to manually write: ✔ getters ✔ constructors ✔ equals() ✔ hashCode() ✔ toString() Java auto-generates all of these. Your class becomes crystal clear about what it stores. 🔹 2. Immutable Data by Design Records are inherently final & immutable, making them: ✔ Thread-safe ✔ Predictable ✔ Side-effect-free Perfect for modern architectures using events, messages, DTOs, and API contracts. 🔹 3. Great for Domain Modeling When your class exists only to hold data — User, Order, GeoLocation, Config — Records provide a clean, concise model. 🔹 4. Perfect Fit for Microservices In distributed systems, immutability = reliability. Records shine as: ✔ DTOs ✔ API request/response models ✔ Kafka event payloads ✔ Config objects 🔹 5. Improved Readability & Maintainability A record makes your intent unmistakable: ➡ “This is a data carrier.” Nothing more. Nothing less. 🔹 6. Supports Custom Logic Too You can still add: ✔ validation ✔ static methods ✔ custom constructors ✔ business constraints …without losing the simplicity. 🔥 Architect’s Takeaway Records encourage immutable, predictable, low-boilerplate designs — exactly what you need when building scalable enterprise systems and clean domain models. Are you using Records in your project instead of POJOs? #100DaysOfJavaArchitecture #Java #JavaRecords #Microservices #CleanCode #JavaDeveloper #TechLeadership
To view or add a comment, sign in
-
-
🚀 Java Streams in Action: Partitioning Data ! 👉 Partition employees into two groups - one earning above ₹50,000 and the others. i. Have you ever needed to split data into two groups based on a condition? ii. Here’s a simple example using Java Streams to partition employees based on salary. 🔍 Approach 👉 stream() Converts the list into a stream to perform functional-style operations. 👉 filter(Objects::nonNull) Removes any null objects from the list to avoid NullPointerException. 👉 collect(...) Terminal operation that transforms the stream into a collection (in this case, a Map). 👉 Collectors.partitioningBy(...) This is the key part 🔥 It splits the data into two groups based on a condition: true -> Employees earning more than ₹50,000 false -> Employees earning ₹50,000 or less ✔ Automatically groups into two categories ✔ Ideal for binary conditions (true/false) 📊 Output Structure true -> List of high-salary employees false -> List of other employees - Use partitioningBy when your condition results in only two groups. - If you need multiple groups (like department-wise), go for groupingBy. 💻 I’ve added my Java solution in the comments below. Please let me know if there are any other approaches I could try. #Java #JavaStreams #CodingInterview #BackendDevelopment #SpringBoot #Developers
To view or add a comment, sign in
-
-
Lazy vs Eager Loading — The N+1 Problem Every Java Dev Must Know One of the most common performance killers in Spring Data JPA is the infamous N+1 query problem — and it all starts with how you configure your fetch strategy. By default, @OneToMany and @ManyToMany use LAZY loading — related data is fetched only when accessed. Meanwhile, @ManyToOne and @OneToOne default to EAGER — data is loaded immediately with the parent. The trap? When you load a list of 100 customers and then access their orders in a loop: List<Customer> customers = customerRepo.findAll(); // 1 query for (Customer c : customers) { c.getOrders().size(); // 100 more queries! } // Total: 101 SQL queries = performance disaster Solutions that actually work: // 1. JOIN FETCH in JPQL @Query("SELECT c FROM Customer c JOIN FETCH c.orders") List<Customer> findAllWithOrders(); // 2. @EntityGraph @EntityGraph(attributePaths = {"orders"}) List<Customer> findAll(); Rule of thumb: ✅ Keep FetchType.LAZY as default ✅ Use JOIN FETCH or @EntityGraph when you know you need related data ✅ Enable Hibernate SQL logging to detect N+1 early ❌ Never switch everything to EAGER — that's trading N+1 for over-fetching #Java #SpringBoot #BackendDevelopment #SpringDataJPA #Performance #LearningInPublic
To view or add a comment, sign in
-
-
🚀 Evolution of Database Interaction in Java (🔧➡️⚙️➡️🚀) It’s fascinating how the “most natural way” to work with databases has evolved over time 👇 🔹 JDBC You write everything manually—queries, connections, result parsing. Full control, but a lot of boilerplate. 🔹 Hibernate ORM We move to object mapping. Less SQL, more Java objects. Cleaner, but still requires configuration and understanding ORM behavior. 🔹 Spring Boot with JPA Things get easier. Auto-configuration, reduced setup, better integration. Focus shifts more toward business logic. 🔹 Spring Data JPA (Repository methods) 🤯 Now this feels like magic! Define methods → Framework generates queries → Minimal SQL needed. 👉 From writing complex SQL to just defining method names… we’ve come a long way. 💡 But here’s the reality: Every layer matters. Understanding JDBC and SQL makes you a stronger developer—even when using high-level abstractions. 📌 Abstraction reduces effort, but fundamentals build mastery. What’s your preferred way of interacting with databases? 👇 #Java #SpringBoot #JPA #Hibernate #BackendDevelopment #SoftwareEngineering #LearningJourney
To view or add a comment, sign in
-
-
What is var? var lets the compiler infer the data type of a local variable from the assigned value. With Java’s Local Variable Type Inference (var), we can write cleaner and more readable code — but only if we understand its boundaries. According to Oracle Docs: 🔗 https://lnkd.in/dzPr83eS Here are 8 practical rules every Java developer must know 1. Works with Different Data Types var name = "Alok"; // String var age = 19; // int var salary = 50000.5; // double Compiler infers the type at compile time. 2. Only for Local Variables public void demo() { var x = 10; // ✅ valid } var is limited to local scope only. 3. Not for Instance or Global Variables class Test { var x = 10; // ❌ compile-time error } 4. Not a Generic Type var list = new ArrayList<String>(); // ✅ var<String> list = new ArrayList<>(); // ❌ 5. No Explicit Generic Declaration with var You can’t mix var with explicit type parameters. ⚠️ 6. Must Be Initialized var x; // ❌ error Compiler needs a value to infer the type. 7. Not Valid for Lambda (Without Target Type) var f = () -> {}; // ❌ error Lambdas require a target type. 8. Not for Method Parameters or Return Types public var getData() { } // ❌ 💡 Key Insight: var reduces boilerplate but Java is still strongly typed — the type is inferred at compile time, not dynamic. Pro Tip: Use var when the type is obvious → avoid it when readability suffers. A big thank you to my mentor Syed Zabi Ulla & PW Institute of Innovation for continuous support and guidance. Your insights and encouragement have played a huge role in shaping my learning journey. #Java #Programming #Developers #Coding #JavaTips #SoftwareEngineering #Learning
To view or add a comment, sign in
-
-
Spring Boot DAY 21 –PathVariable vs RequestParam Understanding the difference between @PathVariable and @RequestParam is very important while building REST APIs 👇 Both are used to extract data from the URL, but they serve different purposes. --- 🔹 1️⃣ @PathVariable ✔ Used to extract values from the URL path ✔ Part of the resource identity ✔ Mandatory by default ✅ Example URL: /users/10 ✅ Code Example: java @GetMapping("/users/{id}") public String getUser(@PathVariable int id) { return "User ID: " + id; } 👉 Here, 10 is part of the URL path. 👉 It represents a specific resource (User with ID 10). 📌 Mostly used when: Fetching single record Updating a specific resource Deleting a specific resource --- 🔹 2️⃣ @RequestParam ✔ Used to extract values from query parameters ✔ Used for filtering, sorting, searching ✔ Can be optional ✅ Example URL: /users?id=10 ✅ Code Example: java @GetMapping("/users") public String getUserById(@RequestParam int id) { return "User ID: " + id; } 👉 Here, id=10 is passed as a query parameter. 👉 Mostly used for filtering or optional data. 📌 Example: /users?city=Nashik /users?page=1&size=5 /users?sort=asc 💡 When to Use What? 👉 Use @PathVariable when the value is required to uniquely identify a resource. 👉 Use @RequestParam when passing optional filters or additional parameters. 🎯 Interview Tip: If the data changes the identity of the resource → use PathVariable If the data modifies how results are returned → use RequestParam
To view or add a comment, sign in
-
-
Stack vs Heap Memory in Java – Where Does Your Data Live? 🧠 Stack Memory: ▸ Method calls + local variables ▸ LIFO (Last In, First Out) ▸ Very fast, auto-cleared after method ends ▸ Each thread has its own stack Heap Memory: ▸ Stores objects & instance variables ▸ Shared across threads ▸ Managed by Garbage Collector ▸ Slower than Stack, can throw OutOfMemoryError Example: void demo() { int x = 10; String s = new String("Java"); } ▸ x → Stack ▸ s (reference) → Stack ▸ "Java" object → Heap Rule: → Primitives → Stack → References → Stack → Objects → Heap #Java #SpringBoot #BackendDevelopment #Memory #JavaDeveloper
To view or add a comment, sign in
-
-
Stack vs Heap Memory in Java – Where Does Your Data Live? 🧠 Stack Memory: ▸ Method calls + local variables ▸ LIFO (Last In, First Out) ▸ Very fast, auto-cleared after method ends ▸ Each thread has its own stack Heap Memory: ▸ Stores objects & instance variables ▸ Shared across threads ▸ Managed by Garbage Collector ▸ Slower than Stack, can throw OutOfMemoryError Example: void demo() { int x = 10; String s = new String("Java"); } ▸ x → Stack ▸ s (reference) → Stack ▸ "Java" object → Heap Rule: → Primitives → Stack → References → Stack → Objects → Heap #Java #SpringBoot #BackendDevelopment #Memory #JavaDeveloper
To view or add a comment, sign in
-
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