50 Days of Java Streams Challenge – Day 5 & Day 6 Consistency is building confidence. Here are two new problems solved using Stream API 👇 ✅ Day 5: Find Missing Numbers Between Min and Max Given an unsorted list, find numbers missing between smallest and largest. List<Integer> numbers = Arrays.asList(10, 14, 19); int min = numbers.stream().min(Integer::compare).get(); int max = numbers.stream().max(Integer::compare).get(); List<Integer> missingNumbers = IntStream.rangeClosed(min, max) .filter(n -> !numbers.contains(n)) .boxed() .collect(Collectors.toList()); System.out.println(missingNumbers); 📌 Output: [11, 12, 13, 15, 16, 17, 18] 🔎 Concepts Used: min() & max() IntStream.rangeClosed() filter() boxed() ✅ Day 6: Group Strings by Their Length A good question to test understanding of groupingBy. List<String> words = Arrays.asList("Java", "Code", "Stream", "API", "Spring"); Map<Integer, List<String>> groupedByLength = words.stream() .collect(Collectors.groupingBy(String::length)); System.out.println(groupedByLength); 📌 Sample Output: {3=[API], 4=[Java, Code], 6=[Stream, Spring]} 🔎 Concepts Used: groupingBy() #Java #JavaStreams #CodingChallenge #BackendDeveloper #InterviewPreparation #LearningInPublic
Java Streams Challenge: Missing Numbers & String Grouping
More Relevant Posts
-
🧩 Java Streams — The Hidden Power of partitioningBy() Most developers treat Streams like filters 🔍 But sometimes you don’t want one result — you want two outcomes at the same time ⚖️ That’s where Collectors.partitioningBy() shines ✨ 🧠 What it really does It splits one collection into two groups based on a condition One stream ➜ Two results ➜ True group & False group 🪄 No manual if-else loops anymore — Java handles it internally 🤖 📦 What it returns (Very Important ⚠️) partitioningBy() returns: Map<Boolean, List<T>> Meaning: ✅ true → elements satisfying condition ❌ false → elements not satisfying condition Example thinking 💭: numbers > 10 true → [15, 18, 21] false → [3, 4, 8, 10] 🚨 Important Note partitioningBy() is NOT a Stream method It belongs to Collectors 🏗️ And is used inside the terminal operation: collect(...) So the stream ends here 🏁 🔬 Internal Structure Insight The result behaves like: Boolean → Collection of matching elements Typically implemented as a HashMap 🗂️ Key = Boolean 🔑 Value = List 📚 🎯 When to use it? Use partitioningBy when: You need exactly two groups ✌️ Condition-based classification 🧩 Cleaner replacement for loops + if/else 🧹 If you need many groups ➜ use groupingBy 🧠 🪄 One-line memory rule groupingBy → many buckets 🪣🪣🪣 partitioningBy → two buckets 🪣🪣 GitHub Link: https://lnkd.in/gxthzFgb 🔖Frontlines EduTech (FLM) #java #coreJava #collections #BackendDevelopment #Programming #CleanCode #ResourceManagement #Java #Java8 #Streams #FunctionalProgramming #AustraliaJobs #SwitzerlandJobs #NewZealandJobs #USJobs #partioningBy #groupingViaStreams
To view or add a comment, sign in
-
-
Java 8 came out over 10 years ago. And it still breaks interviews in 2026. Here are the 8 features that changed everything (and what they actually replaced): → 1. Lambda Expressions Before: 10 lines of anonymous class boilerplate. After: (a, b) -> a.compareTo(b) One line. Same result. No excuses. → 2. Stream API Stop writing for-loops to filter lists. list.stream().filter().map().collect() reads like English. Your future self will thank you. → 3. Optional NullPointerException is the most common Java error in production. Optional.ofNullable() forces you to handle the null case explicitly. This alone will save you hours of debugging. → 4. Functional Interfaces Predicate. Function. Consumer. Supplier. 4 interfaces that make your code composable, testable, and clean. → 5. Method References names.forEach(System.out::println) Instead of: names.forEach(n -> System.out.println(n)) Small change. Huge readability boost. → 6. Default Methods in Interfaces You can now add new methods to interfaces without breaking every class that implements them. This is how Java evolved the Collections API without breaking your code. → 7. New Date/Time API LocalDate. LocalTime. ZonedDateTime. Finally — date handling that is immutable, thread-safe, and actually makes sense. RIP java.util.Date. → 8. Collectors API groupingBy(). joining(). partitioningBy(). Turn raw lists into maps, strings, and partitions — in one line. Java 8 wasn't just an update. It was a shift in how we think about writing Java. From imperative → declarative. From verbose → expressive. From fragile → safe. If you're still on Java 7 patterns in a Java 17+ codebase — this is your sign. Which of these 8 features do you use the most? Drop it in the comments 👇 #Java #Java8 #SoftwareEngineering #Programming #BackendDevelopment
To view or add a comment, sign in
-
-
Revision | Day 4 - Java Collections Framework + Exception Handling Key concepts I reviewed: ✅ List – Ordered collection that allows duplicates Examples: ArrayList, LinkedList ✅ Set – Does not allow duplicate elements Examples: HashSet, LinkedHashSet, TreeSet ✅ Map – Stores key-value pairs Examples: HashMap, LinkedHashMap, TreeMap Some important points: • ArrayList vs LinkedList – ArrayList is faster for random access, LinkedList is better for insert/delete operations. • HashSet uses hashing to store unique elements. • HashMap stores data as key-value pairs and allows one null key. 💡 Collections are heavily used in backend development and frequently asked in interviews. Exception Handling in Java, which helps build reliable and stable applications by handling runtime errors properly. 1. try – Used to write code that might throw an exception 2. catch – Handles the exception 3. finally – Executes important code regardless of exception 4. throw – Used to explicitly throw an exception 5. throws – Declares exceptions in method signatures Types of Exceptions: 1. Checked Exceptions Handled at compile time Example: IOException, SQLException 2. Unchecked Exceptions Occur at runtime Example: NullPointerException, ArithmeticException #Java #BackendDevelopment #JavaDeveloper #SoftwareEngineering #SpringBoot #LearningInPublic #Backend #software #developer #batch2026 #developer #Spring
To view or add a comment, sign in
-
-
🚀 #WhyGoroutinesAreLightweight? 1️⃣ Very Small Initial Stack Size * A goroutine starts with ~2 KB stack (can grow dynamically). * A Java thread typically starts with ~1 MB stack (configurable, but large by default). 👉 That means you can run hundreds of thousands of goroutines in the same memory where you could only run thousands of threads. 2️⃣ #Managed by Go Runtime (Not OS) * Java threads = 1:1 mapping with OS threads. * Goroutines = M:N scheduler model This means: * Many goroutines (N) are multiplexed onto fewer OS threads (M). * Go runtime scheduler decides which goroutine runs. This reduces: * OS context switching cost * Kernel-level overhead 3️⃣ #CheapContextSwitching Switching between goroutines: * Happens in user space * Much faster than OS thread switching * Does not require kernel involvement Java threads: * Context switching handled by OS * More expensive 4️⃣ #EfficientBlockingModel When a goroutine blocks (e.g., I/O): * Go runtime parks it * Another goroutine runs on the same thread In Java: Blocking thread often blocks OS thread (unless using async frameworks) 5️⃣ #DynamicStackGrowth Goroutines: * Stack grows and shrinks automatically * Memory efficient Java threads: * Fixed stack size * Allocated upfront Summary Feature Goroutine Java Thread Stack Size ~2KB (dynamic) ~1MB (fixed) Scheduling. Go runtime OS Context Switching User-level Kernel-level Scalability. Massive Limited 🔥 Real Example You can easily spawn: for i := 0; i < 100000; i++ { go process() } Try doing that with 100,000 Java threads 😅 — you’ll likely run out of memory. #TechCareers #SoftwareEngineer #BackendEngineer #Developers #TechCommunity #CodingLife #golangdeveloper
To view or add a comment, sign in
-
-
Still using loops in Java? You might be missing something powerful… 🚀 Day 6 of Prepare with Pankaj 💻 🔹 What is Stream? A Stream is a sequence of elements used to process collections (List, Set) in a functional and efficient way. 🔹 Why use Streams? ✔ Less code (no complex loops) ✔ Better readability ✔ Easy parallel processing 🔹 Common Operations: 👉 filter() Used to filter data Example: Get only even numbers 👉 map() Used to transform data Example: Multiply each number by 2 👉 collect() Used to collect the result into a List or Set 🔹 Simple Example: import java.util.*; import java.util.stream.*; public class Main { public static void main(String[] args) { List<Integer> list = Arrays.asList(1, 2, 3, 4, 5); List<Integer> result = list.stream() .filter(n -> n % 2 == 0) .map(n -> n * 2) .collect(Collectors.toList()); System.out.println(result); } } 💡 Conclusion: Streams help you write clean, concise, and efficient code. Must-know for every Java developer! #Java #Java8 #Streams #BackendDeveloper #Coding #PrepareWithPankaj 🚀
To view or add a comment, sign in
-
-
🚀 Java 8 Series – Day 9 Collectors – Turning Streams into Useful Results So far we learned: filter() map() flatMap() reduce() But in real projects, we rarely use reduce() directly. Most of the time, we use: collect() What is collect()? collect() is a Terminal Operation. It transforms stream elements into a Collection or Map. It works with the Collectors utility class. Most Common Collectors (Used in Real Projects) 1️⃣ toList() List names = students.stream() .map(Student::getName) .collect(Collectors.toList()); 2️⃣ toSet() .collect(Collectors.toSet()) Removes duplicates automatically. 3️⃣ joining() List names = Arrays.asList("Ali", "Zara", "John"); String result = names.stream() .collect(Collectors.joining(", ")); Output: Ali, Zara, John 4️⃣ groupingBy() 🔥 (Very Important) Suppose we have: class Employee { String name; String department; } Group employees by department: Map<String, List> result = employees.stream() .collect(Collectors.groupingBy(Employee::getDepartment)); This is heavily used in backend APIs. 5️⃣ partitioningBy() Divide elements into two groups based on a condition. Example: Map<Boolean, List> result = numbers.stream() .collect(Collectors.partitioningBy(n -> n % 2 == 0)); Even numbers → true Odd numbers → false Interview Question: What is the difference between groupingBy() and partitioningBy()? Answer: groupingBy() → Multiple groups partitioningBy() → Only two groups (true/false) Why Collectors Matter in Real Projects? • Transform DB results • Group API responses • Create summary reports • Convert data into Maps • Clean business logic Tomorrow: Parallel Streams – When to use & when NOT to use 🔥 Follow the series if you're preparing for serious backend interviews 🚀 #Java #Java8 #StreamAPI #Collectors #BackendDevelopment #SpringBoot #InterviewPreparation
To view or add a comment, sign in
-
What’s New in Java 26 (Key Features Developers Should Know) 1. Pattern Matching Enhancements Java continues improving pattern matching for switch and instanceof. Example: if (obj instanceof String s) { System.out.println(s.toUpperCase()); } Why it matters: Cleaner, safer type checks with less boilerplate. 2. Structured Concurrency (Evolving) Helps manage multiple concurrent tasks as a single unit. Example: try (var scope = new StructuredTaskScope.ShutdownOnFailure()) { scope.fork(() -> fetchUser()); scope.fork(() -> fetchOrders()); scope.join(); } Why it matters: Simplifies multi-threaded code and error handling. 3. Scoped Values (Better than ThreadLocal) A safer alternative to ThreadLocal for sharing data. Example: ScopedValue<String> user = ScopedValue.newInstance(); ScopedValue.where(user, "admin").run(() -> { System.out.println(user.get()); }); Why it matters: Avoids memory leaks and improves thread safety. 4. Virtual Threads Improvements Virtual threads continue to mature (Project Loom). Example: Thread.startVirtualThread(() -> { System.out.println("Lightweight task"); }); Why it matters: Handle thousands of concurrent requests with minimal resources. 5. Foreign Function & Memory API (Stabilization) Interact with native code without JNI. Example: MemorySegment segment = Arena.ofAuto().allocate(100); Why it matters: High-performance native integration (AI, ML, system-level apps). 6. Performance & GC Improvements Ongoing improvements in: - ZGC - G1 GC - Startup time - Memory efficiency Why it matters: Better latency and throughput for large-scale applications. 7. String Templates (Further Refinement) Simplifies string formatting and avoids injection issues. Example: String name = "Java"; String msg = STR."Hello \{name}"; Why it matters: Cleaner and safer string construction. Stay updated, but adopt carefully especially for non-LTS releases. #Java #Java26 #BackendEngineering #SpringBoot #Concurrency #Performance #SoftwareEngineering
To view or add a comment, sign in
-
🚀 15 Days of Java 8 – #Day5: Transforming with `map()` What is the `map()` operation in streams, and how is it different from `filter()`? ✅ Answer: The `map()` operation is an intermediate operation that transforms each element of a stream into another object by applying a function to it. While `filter()` selects elements, `map()` changes them. - `filter(n -> n > 5)`: Takes an `Integer` and returns a `boolean`. The stream remains a stream of `Integer`s. - `map(s -> s.length())`: Takes a `String` and returns an `int`. The stream of `String`s is transformed into a stream of `Integer`s. //--- Code Snippet: Get a list of names' lengths --- List<String> names = Arrays.asList("Alice", "Bob", "Charlie"); List<Integer> nameLengths = names.stream() .map(name -> name.length()) .collect(Collectors.toList()); // Result: [5, 3, 7] //---------------------------------------------------- 💡 Takeaway: Use `filter()` when you want to reduce the number of elements in a stream. Use `map()` when you want to transform each element into something else. 📢 Filtering and mapping are the two most fundamental stream operations! 🚀 Day 6: Chaining operations into a pipeline! 💬 How would you use `map` to convert a list of strings to all uppercase? 👇 #Java #Java8 #StreamAPI #Map #FunctionalProgramming #DataTransformation #15DaysOfJava8
To view or add a comment, sign in
-
🚀 15 Days of Java 8 – #Day8: Other Terminal Operations Besides `collect()`, what are some other common terminal operations in the Stream API? ✅ Answer: While `collect()` is very flexible, there are other simpler terminal operations for specific tasks: - `forEach(action)`: Performs an action for each element of the stream. (e.g., printing each element). - `count()`: Returns the number of elements in the stream as a `long`. - `findFirst()` / `findAny()`: Returns an `Optional` describing the first element of the stream, or any element for parallel streams. - `anyMatch(predicate)` / `allMatch(predicate)`: Returns a `boolean` indicating if any/all elements match a given predicate. //--- Code Snippet --- List<String> names = Arrays.asList("Alice", "Bob", "Charlie"); // Count names starting with 'A' long count = names.stream().filter(s -> s.startsWith("A")).count(); // 1 // Check if any name has more than 5 characters boolean anyLongNames = names.stream().anyMatch(s -> s.length() > 5); // true //-------------------- 💡 Takeaway: Choose the simplest terminal operation that fits your needs. If you just need a count or a boolean check, `count()` or `anyMatch()` are much more direct than using `collect()`. 📢 Many of these operations help avoid writing complex loops and stateful variables. 🚀 Day 9: Let's do a coding challenge! 💬 What is the difference between `findFirst()` and `findAny()`? 👇 #Java #Java8 #StreamAPI #CoreJava #InterviewPrep #15DaysOfJava8
To view or add a comment, sign in
-
🚀Why String is Immutable in Java? — Explained Simply🧠💡!! 👩🎓In Java, a String is immutable, which means once a String object is created, its value cannot be changed. If we try to modify it, Java creates a new String object instead of changing the existing one. 📌But why did Java designers make Strings immutable? 🤔 ✅ 1️⃣ Security Strings are widely used in sensitive areas like database URLs, file paths, and network connections. Immutability prevents accidental or malicious changes. ✅ 2️⃣ String Pool Optimization Java stores Strings in a special memory area called the String Pool. Because Strings are immutable, multiple references can safely share the same object — saving memory. ✅ 3️⃣ Thread Safety Immutable objects are naturally thread-safe. Multiple threads can use the same String without synchronization issues. ✅ 4️⃣ Performance & Caching Hashcodes of Strings are cached. Since values never change, Java can reuse hashcodes efficiently, improving performance in collections like HashMap. 🧠 Example: String name = "Java"; name = name.concat(" Dev"); Here, the original "Java" remains unchanged, and a new object "Java Dev" is created. 🚀 Understanding small concepts like this builds strong Core Java fundamentals and helps you write better, safer, and optimized code. #Java #CoreJava #Programming #JavaDeveloper #CodingConcepts #SoftwareEngineering #LearningEveryday #Parmeshwarmetkar
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