🚀 Java Streams in Action: Sum of Squares of Even Numbers Ever wondered how to write clean and functional-style code in Java? Here's a simple yet powerful example using Streams API 💡 🎯 Problem: From a list of integers, calculate the sum of squares of even numbers. 💻 Solution using Streams: List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6); int sum = numbers.stream() .filter(n -> n % 2 == 0) // Step 1: Filter even numbers .map(n -> n * n) // Step 2: Square each number .reduce(0, Integer::sum); // Step 3: Sum all values System.out.println("Sum of squares of even numbers: " + sum); 🔍 How it works: filter() → selects only even numbers map() → transforms each number into its square reduce() → aggregates the result into a single sum ✨ Output: Sum of squares of even numbers: 56 🔥 Why use Streams? Cleaner and more readable code Functional programming style Easy to parallelize 💬 Have you tried solving similar problems using Streams? Share your thoughts or alternative approaches below! #Java #Streams #Coding #FunctionalProgramming #Developers #JavaDeveloper #Programming #Tech
Java Streams Sum of Squares of Even Numbers
More Relevant Posts
-
🚀 Comparable in Java — Why & When to Use It? Sorting objects in Java becomes simple when you understand Comparable. Let’s break it down 👇 🔹 What is Comparable? Comparable is used to define the natural (default) sorting order of objects within a class. 🔹 Why Use Comparable? ✔ To define a default sorting logic inside the class ✔ Makes sorting easy using "Collections.sort()" or "Arrays.sort()" ✔ Avoids writing external sorting logic again and again 🔹 When to Use Comparable? ✔ When objects have a natural order (like ID, age, name) ✔ When sorting is required frequently ✔ When you want a single standard sorting rule 🔹 Steps to Implement Comparable 1️⃣ Implement "Comparable<T>" in your class 2️⃣ Override "compareTo()" method 3️⃣ Define comparison logic (this vs other object) 4️⃣ Use "Collections.sort()" to sort objects 💡 Key Insight: «Comparable = Natural sorting (inside the class)» 🔥 Mastering this makes your code cleaner and interview-ready #Java #CoreJava #Comparable #Sorting #Collections #Programming #CodingInterview #Developers #SoftwareDevelopment #LearnJava 🚀
To view or add a comment, sign in
-
-
☕ Java Functions (Methods) Explained A function (method) in Java is a block of code designed to perform a specific task. It helps in making code reusable and organized. . . 🔹 Parameters → Variables defined in the method to receive input values 🔹 Arguments → Actual values passed to the method when it is called . 💡 Example: If a method is defined as add(int a, int b) → a and b are parameters When calling add(5, 10) → 5 and 10 are arguments . . Why we use functions? ✨ Using functions makes code cleaner, efficient, and easier to maintain. #Java #Programming #Coding #Developers #postoftheday #linkedinpost #frontend #knowledge
To view or add a comment, sign in
-
-
Day14 Java Practice: Maximum Product of Three Elements in an Array While practicing Java, I solved an interesting array problem: 👉 Find the maximum product that can be formed using any three elements from the array. Example: Input: {10, 3, 5, 6, -20} At first, it looks like we just need the three largest numbers. But the twist is: negative numbers can change the result! 🧠 Key Idea: The product of two negative numbers becomes positive So we must compare: Product of the three largest numbers Product of two smallest (most negative) numbers and the largest number ================================================= // Online Java Compiler // Use this editor to write, compile and run your Java code online import java.util.*; class Main { public static void main(String[] args) { int a [] ={10,3,5,6,-20}; Arrays.sort(a); int n=a.length; System.out.println(Arrays.toString(a)); int result1=a[n-1]*a[n-2]*a[n-3]; int result2=a[0]*a[1]*a[n-1]; int result =Math.max(result1,result2); System.out.println(result); } } Output:[-20, 3, 5, 6, 10] 300 #JavaDeveloper #Arrays #CodingPractice #QualityEngineering #TechLearning
To view or add a comment, sign in
-
-
⚡ Few powerful Java methods every developer should know Some Java methods look small… but they unlock powerful behavior under the hood. Here are a few that are worth understanding 👇 🔹 Class.forName() Loads a class dynamically at runtime 👉 Commonly used when the class name is not known at compile time (e.g., drivers, plugins) 🔹 Thread.yield() Hints the scheduler to pause the current thread 👉 Gives other threads a chance to execute (not guaranteed, just a suggestion) 🔹 String.intern() Moves a String to the String Pool (if not already present) 👉 Helps save memory by reusing identical string values 🔹 map.entrySet() Returns a set of key-value pairs from a Map 👉 Most efficient way to iterate both key and value together 🔹 Object.wait() Makes a thread wait until another thread notifies it 👉 Used for inter-thread communication (must be inside synchronized block) 🔹 Thread.join() Pauses current thread until another thread finishes 👉 Useful when execution order matters 🔹 stream().flatMap() Flattens nested data structures into a single stream 👉 Perfect for transforming lists of lists into a single list 💡 Why these matter? These methods touch core areas of Java: • Concurrency • Memory optimization • Collections • Functional programming Understanding them helps you write cleaner, more efficient code. 📌 Which one do you use most often? #Java #Programming #SoftwareDevelopment #Coding #BackendDevelopment #Tech
To view or add a comment, sign in
-
ERRORS & EXCEPTIONS IN JAVA — SIMPLE & CLEAR WHAT IS AN ERROR? An Error is a serious problem that occurs due to system failure, and we cannot handle it in our program. TYPES OF ERRORS & WHY THEY OCCUR Compile-Time Error • Occurs during compilation • Happens due to wrong syntax (faulty grammar) Examples: - Missing semicolon - Wrong keywords - Incorrect method syntax Runtime Error • Occurs during execution • Happens due to lack of system resources Examples: - StackOverflowError → infinite method calls - OutOfMemoryError → memory is full WHY ERRORS OCCUR (IN ONE LINE): Because of system limitations or wrong program structure WHAT IS AN EXCEPTION? An Exception is a problem caused by the program logic, and we can handle it using try-catch. TYPES OF EXCEPTIONS & WHY THEY OCCUR Checked Exception (Compile Time) • Checked by compiler • Must handle using try-catch or throws WHY IT OCCURS: Because we are using methods that declare exceptions (ducking), so Java forces us to handle or pass them Examples: - IOException → file not found - InterruptedException → thread interruption Unchecked Exception (Runtime) • Not checked by compiler • Occurs during execution WHY IT OCCURS: Because of logical mistakes in program Examples: - ArithmeticException → divide by zero - NullPointerException → using null object FINAL ONE-LINE DIFFERENCE Error → System problem Exception → Programmer mistake Simple Understanding: Errors = Cannot fix easily Exceptions = Can handle and continue program #Java #ExceptionHandling #Programming #Coding #Developers #JavaBasics
To view or add a comment, sign in
-
🔍 Java Stream API – Sort Strings by Length Ever wondered how to sort a list of strings based on their length in a clean and functional way? 🤔 Here’s how you can do it using Java Stream API 👇 💻 Code Example: import java.util.*; import java.util.stream.*; public class SortByLength { public static void main(String[] args) { List<String> words = Arrays.asList("apple", "kiwi", "banana", "fig", "watermelon"); List<String> sortedList = words.stream() .sorted(Comparator.comparingInt(String::length)) .collect(Collectors.toList()); System.out.println(sortedList); } } 📌 Output: [fig, kiwi, apple, banana, watermelon] 💡 Why use Streams? ✔ Cleaner and more readable code ✔ Functional programming style ✔ Less boilerplate 🚀 Mastering Java Streams can make your code more elegant and efficient. Small improvements like this can make a big difference! #Java #StreamAPI #Coding #Programming #Developers #JavaDeveloper #Tech #Learning #CodeSnippet
To view or add a comment, sign in
-
Java Streams vs Traditional Loops — What Should You Use? While working on optimizing some backend logic, I revisited a common question: 👉 Should we use Java Streams or stick to traditional loops? Here’s what I’ve learned 🔹 Traditional Loops (for, while) More control over logic Easier debugging Better for complex transformations List<String> result = new ArrayList<>(); for(String name : names) { if(name.startsWith("A")) { result.add(name.toUpperCase()); } } 🔹 Java Streams Cleaner and more readable Declarative approach Easy parallel processing List<String> result = names.stream() .filter(name -> name.startsWith("A")) .map(String::toUpperCase) .toList(); ⚖️ So what’s better? ✔ Use Streams when: You want clean, functional-style code Working with collections and transformations ✔ Use Loops when: Logic is complex You need fine-grained control My Takeaway: Choosing the right approach matters more than following trends. 💬 What do you prefer — Streams or Loops? #Java #JavaDeveloper #Programming #SoftwareEngineering #BackendDevelopment #Coding #Developers #Tech #Technology #CodeNewbie #JavaStreams #CleanCode #PerformanceOptimization #SystemDesign #SpringBoot #Microservices #FullStackDeveloper #100DaysOfCode
To view or add a comment, sign in
-
🚀 Multithreading in Java — Real-World Example Explained! Ever thought about how apps download multiple files at the same time without slowing down? 🤔 This visual breaks down a simple yet powerful use case of Multithreading in Java — Parallel File Downloads 📂⚡ 🧠 What’s happening behind the scenes? 🧵 Main Thread creates and starts multiple worker threads 📥 Each Thread (t1, t2, t3) handles a separate file ⏱️ All tasks run concurrently, not one after another ⚙️ The JVM scheduler manages execution smartly 🔄 Execution Flow: 1️⃣ Main thread starts all download tasks 2️⃣ Each thread begins downloading its file 3️⃣ Tasks run in parallel (simulated using Thread.sleep) 4️⃣ Files complete independently 5️⃣ Output order may vary due to thread scheduling 💡 Key Insights: ✔️ Multithreading reduces total execution time ✔️ Threads work independently but share CPU resources ✔️ Output is non-deterministic (order can change) ✔️ Ideal for I/O tasks like downloads, APIs, file handling ⚠️ Important Note: Even though each task takes ~2 seconds, 👉 Total time is ~2 seconds (not 6 seconds!) That’s the power of parallel execution 💥 🔥 Where this is used in real life? File downloads (browsers, apps) Video streaming Backend APIs handling multiple users Cloud processing systems 🎯 Takeaway: Multithreading is not just a concept — it’s what makes modern applications fast, responsive, and scalable. #Java #Multithreading #Concurrency #BackendDevelopment #Programming #SoftwareEngineering #Tech #Coding #JavaDeveloper
To view or add a comment, sign in
-
-
I recently explored a subtle but important concept in Java constructor execution order. Many developers assume constructors simply initialize values, but the actual lifecycle is more complex. In this article, I explain: • The real order of object creation • Why overridden methods can behave unexpectedly • A common bug caused by partial initialization This concept is especially useful for interviews and writing safer object-oriented code. Medium Link: https://lnkd.in/gtRhpdfP #Java #OOP #SoftwareDevelopment #Programming
To view or add a comment, sign in
-
🚀 Comparator in Java — When, Why & How to Use It Sorting in Java doesn’t have to be limited to one way. That’s where Comparator comes in 👇 🔹 What is Comparator? Comparator is used to define custom sorting logic outside the class. 🔹 Why Use Comparator? ✔ Allows multiple sorting orders (by name, age, salary, etc.) ✔ Keeps sorting logic separate from the class ✔ Improves flexibility and reusability 🔹 When to Use Comparator? ✔ When you need different ways to sort the same object ✔ When you cannot modify the class (like third-party classes) ✔ When you want clean and maintainable code 🔹 Steps to Use Comparator 1️⃣ Create a class that implements "Comparator<T>" 2️⃣ Override "compare(obj1, obj2)" 3️⃣ Write custom comparison logic 4️⃣ Pass it to "Collections.sort()" or "list.sort()" 💡 Key Insight: «Comparator = Custom sorting (outside the class)» 🔥 Flexible sorting = better design & cleaner code #Java #CoreJava #Comparator #Collections #Sorting #Programming #CodingInterview #Developers #SoftwareDevelopment #LearnJava 🚀
To view or add a comment, sign in
-
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