#Java #java8 1) Intermediate operation. Stream API methods in Java 1. Filtering & Slicing filter(Predicate) – Keeps only elements matching a condition. list.stream().filter(n -> n % 2 == 0).collect(Collectors.toList()); distinct() – Removes duplicates. limit(long maxSize) – Limits the stream to first n elements. skip(long n) – Skips first n elements. --- 2. Mapping & Transforming map(Function) – Transforms each element. list.stream().map(String::toUpperCase).collect(Collectors.toList()); mapToInt, mapToDouble, mapToLong – Maps to primitive streams. flatMap(Function) – Flattens nested structures. listOfLists.stream().flatMap(List::stream).collect(Collectors.toList()); --- 3. Sorting sorted() – Sorts in natural order. list.stream().sorted().collect(Collectors.toList()); sorted(Comparator) – Sorts with custom comparator. list.stream().sorted((a, b) -> b - a).collect(Collectors.toList()); --- 4. Matching & Finding anyMatch(Predicate) – True if any element matches. allMatch(Predicate) – True if all elements match. noneMatch(Predicate) – True if no element matches. findFirst() – Returns first element (optional). findAny() – Returns any element (optional, useful in parallel streams). --- 5. Peeking & Iterating peek(Consumer) – Performs an action on each element (mostly for debugging). list.stream().peek(System.out::println).collect(Collectors.toList()); forEach(Consumer) – Terminal operation to process elements. --- 6. Reducing & Collecting reduce(BinaryOperator) – Combines elements into one. int sum = list.stream().reduce(0, Integer::sum); collect(Collectors.toList()) – Converts stream to list. collect(Collectors.toSet()) – Converts stream to set. collect(Collectors.joining(", ")) – Concatenates strings. collect(Collectors.groupingBy(Function)) – Groups elements by a key. collect(Collectors.partitioningBy(Predicate)) – Splits stream into two groups. --- 7. Other Useful Methods count() – Returns number of elements. min(Comparator) / max(Comparator) – Finds min/max element. toArray() – Converts stream to array. --- ✅ Tips for Intermediate Usage Combine methods for complex queries: list.stream() .filter(n -> n % 2 == 0) .sorted() .map(n -> n * 2) .collect(Collectors.toList()); Use parallelStream() for large datasets. Use peek() for debugging pipelines without altering the stream.
Java Stream API methods: filtering, mapping, sorting, matching, peeking, reducing, collecting, and more.
More Relevant Posts
-
🎯 Modern Java Null Handling: DTO vs Domain Objects - The Right Way! NullPointerException is still the #1 runtime error in Java applications. Let me share a battle-tested approach 👇 📌 The Problem We All Face: Your API receives JSON with nullable fields: { "userId": "123", "email": "user@example.com", "phoneNumber": null, "address": null } Traditional approach? Null checks everywhere! 😫 if (user.getPhone() != null) { if (!user.getPhone().isEmpty()) { sendSMS(user.getPhone()); } } 🎯 The Modern Solution: Layer 1️⃣ - DTO Layer (API Boundary) Keep it nullable for flexibility: public record UserRequest( String userId, String email, String phoneNumber, // nullable AddressDTO address // nullable ) Layer 2️⃣ - Domain Layer (Business Logic) Use Optional for clarity: public class User { private final String userId; private final String email; private final Optional<String> phoneNumber; private final Optional<Address> address; public void sendNotification(NotificationService service) { phoneNumber.ifPresent(phone -> service.sendSMS(phone, "Welcome!") ); address.ifPresentOrElse( addr -> service.sendMail(email, "Delivery: " + addr), () -> service.sendMail(email, "Add delivery address") ); } } Layer 3️⃣ - Safe Conversion public User toDomain() { return new User( userId, email, Optional.ofNullable(phoneNumber) .filter(p -> !p.isBlank()), Optional.ofNullable(address) .map(AddressDTO::toDomain) ); } 🚀 Real-World Benefits: ✅ No Null Checks: Code remains clean and readable ✅ Type Safety: Compiler tells you what's optional ✅ Self-Documenting: Optional clearly means "may not exist" ✅ Stream-Friendly: flatMap(Optional::stream) filters empties elegantly ✅ Testability: Mock-free unit tests, no null edge cases 💡 Golden Rules I Follow: 1️⃣ DTOs can be nullable (API contracts need flexibility) 2️⃣ Domain objects use Optional (business logic clarity) 3️⃣ Never return null from domain methods 4️⃣ Use Optional.ofNullable() at conversion boundaries 5️⃣ Combine with Stream API for powerful filtering ⚡ Power Combo Example: List<String> validPhones = users.stream() .map(User::getPhoneNumber) .flatMap(Optional::stream) // Magic! Filters empties .filter(phone -> phone.startsWith("+91")) .toList(); 🎓 Key Takeaway: The pattern isn't just about Optional - it's about separating concerns: DTOs handle external world (nulls exist) Domain handles business rules (Optional expresses intent) Conversion layer bridges them safely This follows DDD principles while keeping APIs backward-compatible! #Java #CleanCode #SoftwareArchitecture #DomainDrivenDesign #NullSafety #BestPractices #SpringBoot #BackendDevelopment #EnterpriseJava #CodeQuality #Optional #DTO #DDD #JavaDevelopers #SoftwareEngineering #TechTips #Programming #FullStackDevelopment
To view or add a comment, sign in
-
Strings methods in Java 1️⃣ length() Definition: Returns the number of characters in a string (including spaces). 💡 Why it matters: Useful for checking input length (like passwords, usernames) or controlling loops. Example: String name = "Rakshitha"; System.out.println(name.length()); // Output: 9 2️⃣ charAt() Definition: Returns the character at a given index (index starts from 0). 💡 Why it matters: Helps to access or check specific characters, like the first letter of a name. Example: String word = "Java"; System.out.println(word.charAt(2)); // Output: v 3️⃣ toUpperCase() / toLowerCase() Definition: Converts all letters in a string to uppercase or lowercase. 💡 Why it matters: Useful for ignoring case in comparisons or displaying consistent text. Example: String text = "Java"; System.out.println(text.toUpperCase()); // JAVA System.out.println(text.toLowerCase()); // java 4️⃣ equals() / equalsIgnoreCase() Definition: equals() compares two strings exactly, while equalsIgnoreCase() ignores case differences. 💡 Why it matters: Used to compare user inputs like login IDs or names, case-sensitive or not. Example: String a = "Java"; String b = "java"; System.out.println(a.equals(b)); // false System.out.println(a.equalsIgnoreCase(b)); // true 5️⃣ contains() Definition: Checks if a string contains a certain sequence of characters. 💡 Why it matters: Used to search or validate text (like checking if an email contains “@”). Example: String email = "rakshitha@gmail.com"; System.out.println(email.contains("@gmail.com")); // true Awesome 👍 Here are the next 5 common String methods in Java — explained simply with definition, why it matters, and example 👇 6️⃣ substring() Definition: Extracts a part of the string between given start and end indexes. 💡 Why it matters: Used to get a specific portion of text, like extracting username from an email. Example: String word = "JavaDeveloper"; System.out.println(word.substring(0, 4)); // Output: Java 7️⃣ replace() Definition: Replaces all occurrences of a character or substring with another value. 💡 Why it matters: Useful for correcting text, filtering data, or formatting user input. Example: String text = "I love Java"; System.out.println(text.replace("Java", "Python")); // Output: I love Python 8️⃣ split() Definition: Splits a string into multiple parts based on a given delimiter and returns an array. 💡 Why it matters: Used to break text into pieces, such as splitting CSV data or words in a sentence. Example: String data = "apple,banana,grape"; String[] fruits = data.split(","); System.out.println(fruits[1]); // Output: banana 9️⃣ trim() Definition: Removes all leading and trailing spaces from a string. 💡 Why it matters: Essential for cleaning user input before saving or comparing values. Example: String name = " Rakshitha "; System.out.println(name.trim()); // Output: Rakshitha #Java #CoreJava #JavaProgramming #LearnJava #JavaDeveloper
To view or add a comment, sign in
-
hardcore Java internals! 🔥 --- Post 1: Java ka "Class Object" creation ka hidden process!🤯 ```java public class ObjectCreation { public static void main(String[] args) throws Exception { // Ye 3 steps mein hota hai: // 1. Class loading (ClassLoader) Class<?> clazz = Class.forName("java.lang.String"); // 2. Memory allocation (JVM) // 3. Constructor call (<init> method in bytecode) Object obj = clazz.newInstance(); System.out.println(obj.getClass()); // class java.lang.String } } ``` Secret: Har object creation 3 hidden steps mein hoti hai: 1. Loading → 2. Memory allocation → 3. Initialization 💀 --- Post 2: Java ka "Method Signature" internal encoding!🔥 ```java public class MethodSignature { public void show(int a, String b) { } public void show(String a, int b) { } // ✅ Valid - different signature } // Bytecode level par methods ka signature aisa dikhta hai: // show(I Ljava/lang/String;)V // show(Ljava/lang/String; I)V ``` Internal Encoding: · I = int · Ljava/lang/String; = String · V = void return type · Z = boolean · J = long 💡 --- Post 3: Java ka "Type Erasure" ka compiler magic!🚀 ```java import java.util.*; public class TypeErasure { public static void main(String[] args) { List<String> stringList = new ArrayList<>(); List<Integer> intList = new ArrayList<>(); System.out.println(stringList.getClass() == intList.getClass()); // true ✅ } } ``` Output: true Kyun? Compile time pe generics remove ho jate hain! Runtime pe donoArrayList hi hain! 💪 --- Post 4: Java ka "String Concatenation" internal optimization!🔮 ```java public class StringConcat { public static void main(String[] args) { String a = "Hello"; String b = "World"; String result1 = a + b; // StringBuilder use karta hai String result2 = a.concat(b); // Direct concat String result3 = "Hello" + "World"; // Compile time pe "HelloWorld" ban jata hai } } ``` Bytecode Analysis: · a + b → new StringBuilder().append(a).append(b).toString() · a.concat(b) → Direct string manipulation · Constant strings → Compile time pe resolve 💀
To view or add a comment, sign in
-
Java ke atomic level ke secrets! 🔥 --- Post 1: Java ka "Class Loading" ka hidden hierarchy!🤯 ```java public class ClassLoaderSecrets { public static void main(String[] args) { ClassLoader loader = String.class.getClassLoader(); System.out.println(loader); // null ✅ // Kyun? Bootstrap ClassLoader C++ mein implemented hai // Java mein uska koi object nahi hota! } } ``` ClassLoader Hierarchy: 1. Bootstrap (C++ implementation) - null dikhata hai 2. Platform (Java 9+) - jdk.internal.loader.ClassLoaders$PlatformClassLoader 3. Application - sun.misc.Launcher$AppClassLoader Secret: Bootstrap ClassLoader Java mein visible nahi hota! 💀 --- Post 2: Java ka "Lambda Metafactory" internal magic!🔥 ```java public class LambdaSecrets { public static void main(String[] args) { Runnable r = () -> System.out.println("Lambda"); // Internally ye invokeDynamic instruction banata hai // LambdaMetafactory lambda class runtime pe generate karta hai! } } ``` Bytecode Level: ``` invokedynamic #2, 0 // LambdaMetafactory.metafactory() call ``` Internal Process: 1. invokedynamic instruction 2. LambdaMetafactory call 3. Runtime pe synthetic class generation 4. Method handle return 💡 --- Post 3: Java ka "String Deduplication" G1GC feature!🚀 ```java public class StringDedup { public static void main(String[] args) { // G1GC automatically duplicate strings ko same memory point kar deta hai char[] data = {'J', 'a', 'v', 'a'}; String s1 = new String(data); String s2 = new String(data); // G1GC intern() ki tarah same char[] point kar sakta hai! } } ``` JVM Option: ``` -XX:+UseG1GC -XX:+UseStringDeduplication ``` Secret: G1GC duplicate strings ko automatically optimize karta hai! 💪 --- Post 4: Java ka "Stack Walking" internal API!🔮 ```java public class StackWalkSecrets { public static void main(String[] args) { StackWalker walker = StackWalker.getInstance(); walker.forEach(frame -> { System.out.println(frame.getClassName() + "." + frame.getMethodName()); }); } } ``` Internal Stack Frame Structure: · Method name · Class name · Line number · Bytecode index Performance: StackWalker traditionalStackTrace se 10x faster hai! 💀
To view or add a comment, sign in
-
Here are some fun basic Java code snippets to refresh the fundamental understanding. Guess the output! How many did you get right? 1.➡️ public class OverloadExample { public void show(Object obj) { System.out.println("Cat"); } public void show(String str) { System.out.println("Dog"); } public static void main(String[] args) { OverloadExample example = new OverloadExample(); example.show(null); } } 2.➡️ public class ConstructorTest { void ConstructorTest() { System.out.println("Hello"); } public static void main(String[] args) { ConstructorTest ct = new ConstructorTest(); } } 3.➡️ public class IncrementTest { public static void main(String[] args) { int x = 5; System.out.println(x++ + ++x); } } 4.➡️ public class LoopTest { public static void main(String[] args) { int i = 0; for(; i < 3; i++); System.out.println(i); } } 5.➡️ public class BooleanTest { public static void main(String[] args) { boolean b1 = true; boolean b2 = false; System.out.println(b1 & b2); System.out.println(b1 && b2); } } 6.➡️ class Main { public static void main(String[] args) { boolean b = false; System.out.println(b & test()); System.out.println("============================"); System.out.println(b && test()); } public static boolean test() { System.out.println("Called"); return false; } } 7.➡️ public class CastTest { public static void main(String[] args) { double d = 9.78; int i = (int) d; System.out.println(i); } } 8.➡️ public class PrePostTest { public static void main(String[] args) { int x = 2; int y = x++ * 3 + ++x; System.out.println(y); } } 9.➡️ public class CharTest { public static void main(String[] args) { char c = 'A'; c += 1; System.out.println(c); } } 10. ➡️public class LogicalTest { public static void main(String[] args) { int a = 5, b = 10; System.out.println(a < b || b++ < 15); System.out.println(b); } }
To view or add a comment, sign in
-
Understanding the Power of the List Interface in Java If you’ve ever worked with Java Collections, you know that the List interface is one of the most widely used and versatile parts of the framework. It’s more than just a way to store data — it’s a dynamic, flexible, and ordered data structure that adapts to your program’s needs. What is a List in Java? A List in Java is an ordered collection that allows duplicate elements and provides positional access using indexes. Unlike arrays, Lists are resizable, meaning you can add, remove, or modify elements dynamically without worrying about fixed size limitations. It extends the Collection interface and brings in a variety of features that make data handling smoother and more efficient. Key Features of List Maintains insertion order Allows duplicates Index-based access (retrieve or modify using index) Dynamic size (no fixed length like arrays) Supports easy iteration using loops or iterators Common Implementations Java provides multiple implementations of the List interface, each designed for specific use cases: 1. ArrayList Backed by a dynamic array. Best for fast random access and search operations. Slightly slower for insertions and deletions in the middle. 2. LinkedList Based on a doubly linked list. Excellent for frequent insertions and deletions. Slower for random access due to traversal. 3. Vector A synchronized (thread-safe) version of ArrayList. Considered legacy but still useful in multithreaded environments. 4. Stack Extends Vector and follows the LIFO (Last In, First Out) principle. Used in scenarios like expression evaluation or undo operations. Example in Action import java.util.*; public class ListExample { public static void main(String[] args) { List<String> languages = new ArrayList<>(); languages.add("Java"); languages.add("Python"); languages.add("C++"); languages.add("Java"); // duplicates allowed System.out.println("Languages: " + languages); languages.remove("C++"); System.out.println("After removal: " + languages); System.out.println("First element: " + languages.get(0)); } } Output: Languages: [Java, Python, C++, Java] After removal: [Java, Python, Java] First element: Java When to Use Which Use ArrayList for frequent read and search operations. Use LinkedList when insertion or deletion operations are more common. Use Vector or Stack when synchronization or stack-like behavior is required. Final Thought The List interface is a foundation of Java’s data structure ecosystem. Whether you’re building a database system, an Android app, or handling backend data — knowing when and how to use Lists efficiently can significantly improve performance and readability. #Java #Collections #Coding #Programming #SoftwareDevelopment #Learning #TechCommunity #JavaDeveloper
To view or add a comment, sign in
-
-
In Java, there are several ways to create and run threads, Spring Boot also have @Async annotation to run method code as thread. 1. Extending the Thread class You can create a subclass of Thread and override the run() method. ✅ Example: class MyThread extends Thread { @Override public void run() { System.out.println("Thread running " + Thread.currentThread().getName()); } } public class Main { public static void main(String[] args) { MyThread t1 = new MyThread(); t1.start(); } } 🧩 2. Implementing the Runnable interface ✅ Example: class MyRunnable implements Runnable { @Override public void run() { System.out.println("Thread running using Runnable interface: " + Thread.currentThread().getName()); } } public class Main { public static void main(String[] args) { Thread t1 = new Thread(new MyRunnable()); t1.start(); } } 🟢 Why preferred: Allows you to extend another class (since Java supports only single inheritance). ⚡ 3. Using Anonymous Class You can create and start a thread in one line using an anonymous inner class. ✅ Example: public class Main { public static void main(String[] args) { Thread t1 = new Thread(new Runnable() { @Override public void run() { System.out.println("Thread running using Anonymous class"); } }); t1.start(); } } 💡 4. Using Lambda Expression (Java 8+) ✅ Example: public class Main { public static void main(String[] args) { Thread t1 = new Thread(() -> { System.out.println("Thread running using Lambda expression"); }); t1.start(); } } ⚙️ 5. Using ExecutorService (Thread Pool) For multiple or managed threads, use an Executor Service. ✅ Example: import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class Main { public static void main(String[] args) { ExecutorService executor = Executors.newFixedThreadPool(2); executor.submit(() -> System.out.println("Thread 1 using ExecutorService")); executor.submit(() -> System.out.println("Thread 2 using ExecutorService")); executor.shutdown(); } } 🟢 Advantages: Reuses threads (avoids overhead of creating new threads repeatedly) Supports async tasks and better error handling 🧠 6. Using Callable and Future (for return values) Callable is like Runnable, but can return a value and throw exceptions. ✅ Example: import java.util.concurrent.*; public class Main { public static void main(String[] args) throws Exception { ExecutorService executor = Executors.newSingleThreadExecutor(); Callable<String> task = () -> { return "Result from thread: " + Thread.currentThread().getName(); }; Future<String> future = executor.submit(task); System.out.println(future.get()); executor.shutdown(); } }
To view or add a comment, sign in
-
ArrayList(C)(1.2V): ============ Java Array List class uses a dynamic array for storing the elements. It is like an array, but there is no size limit. We can add or remove elements anytime. So, it is much more flexible than the traditional array. It is found in the java.util package. ArrayList is dynamic data structure in which you can add or remove any number of elements. The important points about Java ArrayList class are: ================================== 1. Java ArrayList class can contain duplicate elements. 2. Java ArrayList class maintains insertion order. 3. Not Synchronized: Array-List is not thread-safe. Multiple thread can be access. 4. Java ArrayList allows random access because array works at the index basis. 5. In ArrayList, manipulation is little bit slower than the LinkedList in Java because a lot of shifting needs to occur if any element is removed from the array list. 6. We can not create an array list of the primitive types, such as int, float, char, etc. It is required to use the wrapper class in such cases. For example: ArrayList<int> al = ArrayList<int>(); // does not work ArrayList<Integer> al = new ArrayList<Integer>(); // works fine Note: Java new generic collection allows you to have only one type of object in a collection. Now it is type safe so typecasting is not required at runtime. Advantages of ArrayList: ================ 1. Dynamic Sizing: You don't need to specify the size in advance, and it can grow or shrink dynamically. 2. Indexed Access: Fast access to elements by index, making it ideal for situations where you need to access or modify elements frequently. 3. Supports Duplicates: Can store duplicate elements, unlike Set. 4. Flexibility: It is part of the Collections Framework, so you can easily use it with other collections and utilities (like sorting, searching, etc.). 5. ArrayList is the best choice if our frequent operation is retrieval. Disadvantages of ArrayList: ================= 1. Not Synchronized: ArrayList is not thread-safe by default, so it's not suitable for concurrent modifications by multiple threads. 2. Performance: Inserting or removing elements in the middle or beginning of an ArrayList is slow because it involves shifting elements. 3. Memory Consumption: It may consume more memory than other collections, especially when there are fewer elements than the allocated capacity. 4. ArrayList is the worst choice if our frequent operation is insertion (or) deletion in the middle because it requires several internal shift operations. #InterviewExperience #Java #SpringBoot #BackendDevelopment #Core Java #Basic Concept
To view or add a comment, sign in
-
"🚀 Day 44 of 50 – Java LeetCode Challenge" Today’s challenge was “228. Summary Ranges” — a neat array-based problem that enhances your understanding of iteration, range detection, and string manipulation in Java. The goal is to summarize continuous sequences of numbers into compact range strings. ⏱ Today’s Task – Summary Ranges 📝 Problem Statement: You are given a sorted unique integer array nums. A range [a, b] is defined as all integers from a to b (inclusive). Return the smallest sorted list of ranges that covers all numbers in the array exactly. Each range should be represented as: "a->b" if a != b "a" if a == b 🧪 Examples: Input: nums = [0,1,2,4,5,7] Output: ["0->2","4->5","7"] ✅ Input: nums = [0,2,3,4,6,8,9] Output: ["0","2->4","6","8->9"] ✅ 🔧 Constraints: 0 <= nums.length <= 20 -2³¹ <= nums[i] <= 2³¹ - 1 All values are unique and sorted in ascending order 💻 My Java Solution: import java.util.*; class Solution { public List<String> summaryRanges(int[] nums) { List<String> result = new ArrayList<>(); if (nums.length == 0) return result; int start = nums[0]; for (int i = 1; i < nums.length; i++) { if (nums[i] != nums[i - 1] + 1) { if (start == nums[i - 1]) { result.add(String.valueOf(start)); } else { result.add(start + "->" + nums[i - 1]); } start = nums[i]; } } if (start == nums[nums.length - 1]) { result.add(String.valueOf(start)); } else { result.add(start + "->" + nums[nums.length - 1]); } return result; } } 🔍 Takeaways: ✅ Efficient handling of continuous integer sequences ✅ Smart use of loop tracking and condition checks ✅ Clean, readable implementation with O(n) time complexity ✅ Handles edge cases gracefully (like empty arrays or single elements) 💡 Core Concepts: 📘 Array traversal and pattern detection 📘 String concatenation and list building 📘 Conditional logic for sequence grouping 🎯 Day 44 completed — 6 more to go! 🚀 #Java #50DaysOfCode #LeetCode #ProblemSolving #Arrays #DataStructures #JavaProgramming #Day44 #CodeNewbie #LearnInPublic
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