Ever wondered how to transform a collection of data into a single, powerful result with just a few lines of code? Enter the reduce() method in Java’s Stream API – your secret weapon for folding streams into summaries like sums, products, or custom aggregates! Imagine you have a list of numbers [2, 3, 4, 5, 6]. Using reduce(), we can sum them up starting from an initial value of 0. List<Integer> numbers = Arrays.asList(2, 3, 4, 5, 6); Optional<Integer> sum = numbers.stream() .reduce(0, (x, y) -> x + y); System.out.println(sum.get()); // Output: 20 #Java #StreamAPI #FunctionalProgramming #JavaTips #SoftwareDevelopment
Java Stream API: Summing with reduce() Method
More Relevant Posts
-
📘 LeetCode Daily — Balanced Binary Tree Checked tree balance by recursively comparing left and right subtree heights at every node. The solution worked, but it clearly showed how repeated height calculations increase time complexity—an important reminder that correct logic isn’t always optimal logic. Solid recursion practice and a good lead-in to optimization. #LeetCode #BinaryTree #Recursion #DSA #Java
To view or add a comment, sign in
-
-
50DaysOfStreams – Day 4 ✅ Day 4: Find the First Non-Repeated Character in a String 🧩 Problem: Given a string, find the first non-repeating character using Java Streams. Solution: String input = "swiss"; Optional<Character> result = input.chars() .mapToObj(c -> (char) c) .collect(Collectors.groupingBy( Function.identity(), LinkedHashMap::new, Collectors.counting() )) .entrySet() .stream() .filter(entry -> entry.getValue() == 1) .map(Map.Entry::getKey) .findFirst(); result.ifPresent(System.out::println); Output: w 🛠 Concepts Used: chars() mapToObj() groupingBy() LinkedHashMap (to maintain order) findFirst() See you tomorrow for Day 5 🔥 #Java #Streams #FunctionalProgramming #CodingChallenge #BackendDevelopment #LearningInPublic
To view or add a comment, sign in
-
🧵 Thread in Java – Quick Cheat Sheet 🔹 Thread = Smallest unit of execution 🔹 Multithreading = Multiple threads run inside one process ⚡ 🏗 Thread Creation ✅ Extend Thread ✅ Implement Runnable (preferred – supports inheritance) 🔄 Thread Lifecycle 🆕 New → ▶️ Runnable → ⚙️ Running → ⏸ Waiting/Blocked → ❌ Terminated ⏱ Thread Scheduling 🎯 Priority-based (1–10) ⚠️ Priority is just a hint, JVM + OS decide execution 🔒 Synchronization 🛡 Ensures safe access to shared resources 🚫 Prevents race conditions 🔁 Inter-Thread Communication 📣 wait() | notify() | notifyAll() 🔐 Must be used inside synchronized blocks ❌ Deadlock 🔄 Threads waiting on each other’s locks ⚠️ Caused by improper lock ordering 🛡 Thread Safety ✔ synchronized ✔ Immutable objects ✔ Concurrent collections ⚙️ Concurrency Utilities 🚀 ExecutorService 📦 Callable, Future ⏳ CountDownLatch, Semaphore 💡 Pro Tip: 👉 Prefer ExecutorService over manual thread handling in real projects. #Java #Multithreading #Concurrency #JavaDeveloper #Backend #InterviewPrep #SystemDesign #100DaysOfCode
To view or add a comment, sign in
-
-
Day28 - LeetCode Journey Solved LeetCode 383: Ransom Note in Java ✅ This problem was a great example of how frequency counting can simplify string-based logic. The task was to check whether a ransom note can be constructed using characters from a magazine, with each character usable only once. Using a fixed-size frequency array made the solution clean and efficient. First counting all characters in the magazine and then consuming them while checking the ransom note felt very intuitive. The moment any required character ran out, we could immediately return false. Simple logic, strong impact. What stood out here was how important it is to choose the right data structure. A small optimization like using an array instead of a map makes the solution faster and more memory-efficient. Key takeaways: • Effective use of frequency arrays • Strong practice of string traversal • Early termination for better performance • Writing optimized and readable code ✅ Accepted successfully ✅ 1 ms runtime with top performance Problems like these quietly sharpen your fundamentals. Staying consistent, one problem at a time 💪 #LeetCode #Java #DSA #Strings #ProblemSolving #Algorithms #CodingJourney #InterviewPreparation #DailyPractice #Consistency
To view or add a comment, sign in
-
-
RAG systems usually fail at retrieval, not generation. If the query is vague, no embedding model can fix it later. This article walks through query rewriting as a first-class RAG concern using LangChain4j Query Transformers and Quarkus Easy RAG. No UI tricks. No prompt hacks. Just an explicit architectural step that makes retrieval predictable. If you’re building AI-infused Java systems, this is one of those details that quietly decides whether the system behaves. https://lnkd.in/eWYfNCQh #Java #Quarkus #LangChain4j #RAG #AIEngineering #SoftwareArchitecture #EnterpriseJava
To view or add a comment, sign in
-
-
📝 Day 16/30 – LeetCode #15 (3Sum) | Java This problem extends the two-sum pattern and introduces duplicate handling as the main challenge. A brute-force approach would require checking all triplets, resulting in O(n³) time complexity. By sorting the array and fixing one element, I applied a two-pointer approach on the remaining part of the array. Careful duplicate skipping ensured unique triplets while maintaining efficiency. This optimized the solution to O(n²) time. This problem reinforced how sorting combined with pointer logic can drastically reduce complexity. #LeetCode #Java #DSA #TwoPointers #Arrays #ProblemSolving #Consistency #LearningInPublic
To view or add a comment, sign in
-
-
Abstraction is often explained as “use interfaces” or “hide implementation details.” In real systems, that understanding usually creates more layers, not more clarity. Abstraction is about what clients are allowed to depend on, how change is isolated, and why dependency direction matters. This document captures how I now think about Abstraction — as a way to stabilize systems, and why leaking details silently breaks SOLID. #SoftwareDesign #OOP #BackendEngineering #CleanCode #Abstraction #Java
To view or add a comment, sign in
-
Prompt injection is not a prompt problem. It’s an input authority problem. In this article, I walk through a production-grade approach for Java teams: Enforcing unforgeable input boundaries Separating data from instructions Implementing Spotlighting + StruQ in Quarkus with LangChain4j This is not about catching “bad prompts.” It’s about making them powerless. Read the full breakdown here: https://lnkd.in/dwqRsnYn #Java #Quarkus #LLMSecurity #AIArchitecture #PromptInjection #EnterpriseAI
To view or add a comment, sign in
-
-
🚀 Day 96 of #100DaysOfCode Solved LeetCode #1461 – Check If a String Contains All Binary Codes of Size K ✅ A solid mix of sliding window + bit manipulation, where efficiency really matters. Key Takeaways: -> Using rolling hash / bitmask to track binary substrings -> Avoiding substring overhead for better performance -> Understanding the limit: total required codes = 2^k -> Early pruning with length checks for optimization Language: Java -> Runtime: 6 ms (Beats 100%) ⚡ -> Memory: 47.73 MB Almost at the finish line — one binary string at a time 💻🔥 #LeetCode #Java #BitManipulation #SlidingWindow #Strings #ProblemSolving #100DaysOfCode
To view or add a comment, sign in
-
-
🚀 Day 66 of #100DaysOfCode | Top K Frequent Elements Solved Top K Frequent Elements using an efficient Bucket Sort–based approach in Java. Approach used: Count the frequency of each element using a HashMap Create a bucket array where the index represents frequency Traverse the buckets from highest to lowest frequency to collect the top k elements Why this approach is efficient: No need to sort the entire array Makes use of the frequency range (1 → n) Works well even for large inputs Time & Space Complexity: Time: O(n) Space: O(n) Key takeaways: Bucket Sort is extremely useful for frequency-based problems Understanding constraints leads to optimal solutions Clean logic beats overcomplicated code Consistency is the real win. On to Day 68 💪 #Day67 #DSA #Java #LeetCode #ProblemSolving #CodingJourney #Consistency
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