🚀 15 Days of Java 8 – #Day4: Filtering with Streams How do you use the `filter()` operation in the Stream API to select elements that match a certain criteria? ✅ Answer: The `filter()` operation is an intermediate operation that takes a `Predicate` (a function that returns a boolean) and returns a new stream containing only the elements that match the predicate. //--- Old Way (for-each loop) --- List<String> longNames = new ArrayList<>(); for (String name : names) { if (name.length() > 5) { longNames.add(name); } } //--- New Way (Stream.filter) --- List<String> longNames = names.stream() .filter(name -> name.length() > 5) .collect(Collectors.toList()); //-------------------------------- 💡 Takeaway: The `filter()` operation is your go-to tool for selectively choosing elements from a collection based on a condition. It's the `if` statement of the stream world. 📢 Declarative code is easier to read and reason about! 🚀 Day 5: Transforming elements with `map()`! 💬 How would you filter a list of integers to get only the positive numbers? 👇 #Java #Java8 #StreamAPI #Filter #Lambda #CleanCode #15DaysOfJava8
Filtering with Java 8 Streams: Using filter() Operation
More Relevant Posts
-
🚀 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 – #Day7: Collecting Results with `collect()` What is the role of the `collect()` method, and what is the `Collectors` utility class? ✅ Answer: `collect()` is a terminal operation that transforms the elements of a stream into a different kind of result, like a `List`, `Set`, or `Map`. The `java.util.stream.Collectors` class is a utility class that provides many common implementations of collectors. //--- Code Snippet --- List<String> names = ...; // Collect to a List List<String> nameList = names.stream().collect(Collectors.toList()); // Collect to a Set (removes duplicates) Set<String> nameSet = names.stream().collect(Collectors.toSet()); // Join into a single String String joinedNames = names.stream().collect(Collectors.joining(", ")); //-------------------- 💡 Takeaway: `collect()` is the most versatile terminal operation. It's how you get your data out of the stream pipeline and into a concrete data structure or summary result. 📢 The `Collectors` class is full of powerful tools like `groupingBy` and `summarizingInt`! 🚀 Day 8: `forEach`, `count`, and other terminal operations! 💬 How would you collect stream elements into a `Map`? 👇 #Java #Java8 #StreamAPI #Collectors #Collections #CoreJava #15DaysOfJava8
To view or add a comment, sign in
-
When should you use Optional in Java? 🧠 Optional is powerful but only when used intentionally. ✅ Use it when a method may or may not return a value. If something can be absent, make that absence explicit. Returning null hides the risk. Returning Optional makes the contract clear. It tells the caller: “Handle this properly.” 🔍 That’s good API design. But don’t overuse it 🚫 • Not as entity fields • Not in DTOs • Not as method parameters • Not as a blanket replacement for every null Optional is a design tool not decoration. Simple rule: Use Optional for return types where absence is valid. Avoid spreading it across your entire data model. Clean code isn’t about using more features. It’s about using the right ones with clarity. ⚙️✨ #Java #BackendDevelopment #CleanCode #SoftwareEngineering #SpringBoot
To view or add a comment, sign in
-
🚀 15 Days of Java 8 – #Day12: Method References What is a Method Reference, and how does it make the lambda expression below even more concise? //--- Lambda Expression --- List<String> names = ...; names.stream() .map(s -> s.toUpperCase()) .forEach(s -> System.out.println(s)); //------------------------- ✅ Answer: A Method Reference is a shorthand syntax for a lambda expression that executes just a single, existing method. It's used to make your code even more compact and readable by referring to a method by its name. There are four types: reference to a static method, an instance method of a particular object, an instance method of an arbitrary object of a particular type, and a constructor. //--- With Method References --- List<String> names = ...; names.stream() .map(String::toUpperCase) // Reference to an instance method .forEach(System.out::println); // Reference to an instance method //------------------------------ 💡 Takeaway: If your lambda expression simply calls an existing method, you can often replace it with a more readable method reference (`ClassName::methodName`). 📢 This is pure syntactic sugar, but it makes for very elegant code! 🚀 Day 13: Let's talk about a major change to interfaces - Default Methods! 💬 How would you write a method reference to the `String.valueOf` static method? 👇 #Java #Java8 #MethodReference #Lambda #SyntacticSugar #CleanCode #15DaysOfJava8
To view or add a comment, sign in
-
In new #Java26, Stable Values become Lazy Constants !🔥 A LazyConstant <T> will be a container that holds a single value of type T. Once assigned, that value becomes immutable. You can think of it as an eventually final value. What can you do with those? How may they be useful? And what's changed from Java 25? Here are some answers! https://lnkd.in/dMRk2grY
To view or add a comment, sign in
-
Java 8 : Major and most commonly used Java 8 features, List : 1. Lambda Expressions 2. Functional Interfaces 3. Method References 4. Stream API 5. Parallel Streams 6. Default Methods in Interfaces 7. Static Methods in Interfaces 8. Optional Class 9. New Date and Time API 10. forEach() method in Iterable 11. Collector API 12. CompletableFuture API 13. Nashorn JavaScript Engine 14. Base64 Encoding and Decoding 15. Type Annotations 16. Repeating Annotations 17. Improved Map methods (computeIfAbsent, merge, etc.) #java #java8features
To view or add a comment, sign in
-
🚀 15 Days of Java 8 – #Day11: Using `Optional` Correctly What is wrong with this common misuse of the `Optional` class? //--- Anti-Pattern --- Optional<String> name = findName(); if (name.isPresent()) { System.out.println(name.get()); } //------------------- ✅ Answer: While this code works, it's considered an anti-pattern because it's not much better than a simple `if (name != null)` check. It doesn't use the expressive, functional style that `Optional` was designed to encourage. A much better, more idiomatic way is to use the methods provided by the `Optional` class itself. //--- Better Way --- // Use ifPresent to perform an action only if a value exists findName().ifPresent(name -> System.out.println(name)); // Use orElse to provide a default value String displayName = findName().orElse("Guest"); // Use orElseThrow to throw an exception if the value is absent String requiredName = findName().orElseThrow(() -> new IllegalStateException()); //------------------ 💡 Takeaway: Avoid `.isPresent()` followed by `.get()`. Prefer the functional methods like `ifPresent()`, `map()`, `orElse()`, and `orElseThrow()` to create more fluent and readable code. 📢 Using a feature correctly is as important as knowing it exists! 🚀 Day 12: A shortcut for lambdas - Method References! 💬 The `.get()` method can still throw a `NoSuchElementException`. Can you see why? 👇 #Java #Java8 #Optional #BestPractices #CleanCode #SoftwareDesign #15DaysOfJava8
To view or add a comment, sign in
-
#Day11 of #100DaysofCode Challenge ✨ 📚 Today I Learned: Important Java String & Character Methods While practicing Java, I studied some useful methods that help us clean, check, and modify text in real programs. 🔹 String Methods ✔ trim() Removes spaces at the beginning and end of a string. Example: " hello " → "hello" ✔ toLowerCase() / toUpperCase() Convert all letters to lowercase or uppercase. Example: "Java" → "JAVA" ✔ startsWith() Checks if a string begins with a specific word. Example: "https://google.com" starts with "https" → true ✔ endsWith() Checks if a string ends with a specific word. Example: "mail@gmail.com" ends with "@gmail.com" → true ✔ replace() Replaces all occurrences of a character or word. Example: "teh cat" → "the cat" ✔ replaceFirst() Replaces only the first occurrence. These methods are useful in: 👉 Form validation 👉 Cleaning user input 👉 Checking URLs or emails 🔹 Character Methods These work on single characters. ✔ isLetter() → Checks alphabet ✔ isDigit() → Checks number ✔ isWhitespace() → Checks space ✔ isUpperCase() / isLowerCase() → Check letter case ✔ toUpperCase() / toLowerCase() → Change case ✔ toString() → Convert char → string Useful for: 👉 Password validation 👉 Checking user input 👉 Parsing text Understanding basics clearly helps solve bigger problems later. Learning step by step every day 🚀 #Java #CodingJourney #DSA #Learning #Consistency #ccbp #NxtWave #Developer #JavaFullStack #LearningByDoing Rahul Attuluri
To view or add a comment, sign in
-
💡 Tired of NullPointerException? Meet Optional in Java. For years, Java developers have battled: ❌ Unexpected null values ❌ Endless if checks ❌ Fragile code Then came Java 8 with a smarter solution → Optional. It’s not just a wrapper - it forces us to handle the absence of a value intentionally. 🚀 Why Optional matters ✔ Cleaner, more expressive code ✔ Fewer null checks ✔ Reduced NullPointerException risk ✔ Clearer API design ✔ A step toward functional & modern Java 🔴 Before Optional if (user != null && user.getAddress() != null) { System.out.println(user.getAddress().getCity()); } 🟢 With Optional Optional.ofNullable(user) .map(User::getAddress) .map(Address::getCity) .ifPresent(System.out::println); ⚠️ Use Optional for return types - not for fields, parameters, or serialization. ✨ Small change. Massive improvement in readability, safety, and intent. Optional isn’t just a class - it’s a mindset shift toward writing robust, intentional Java code. #Java #Java8 #Optional #CleanCode #FunctionalProgramming #SoftwareDevelopment
To view or add a comment, sign in
-
💡 The Java Habit That Instantly Made My Code Cleaner One habit improved my Java code more than any framework or library. Naming things properly. Sounds simple, but it’s surprisingly hard. Compare this: int d; vs int daysSinceLastLogin; Or this: processData(); vs calculateMonthlyRevenue(); Good naming does 3 powerful things: ✔ Makes code self-documenting ✔ Reduces the need for excessive comments ✔ Helps other developers understand your logic instantly I realized that most messy code isn't complex — it's just poorly named. Now I follow one rule: 👉 If someone can understand the code without asking me questions, the naming is good. Clean code is not just about algorithms or patterns. Sometimes it's just about choosing better words. 💬 What’s the worst variable or method name you’ve ever seen in a codebase? #Java #CleanCode #SoftwareEngineering #JavaDeveloper #CodingBestPractices #BuildInPublic
To view or add a comment, sign in
-
More from this author
-
How to Build a Portfolio That Gets You Hired as a Java Developer (Even With Zero Experience)
RAMA CHANDRA RAO POLAMARASETTI 🇮🇳 1h -
The 4 Pillars of OOPs That Will Make You a Better Developer (With Real-World Examples)
RAMA CHANDRA RAO POLAMARASETTI 🇮🇳 1w -
5 Reasons Why Most Java Learners Never Get Hired (And How to Fix It)
RAMA CHANDRA RAO POLAMARASETTI 🇮🇳 1w
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