⚡ 10+ Approaches to Find Max or Min Value in Java 8 Streams — Master It Like a Pro 💪 Working with Java 8 Streams? Here are 10 powerful and elegant ways to find the maximum or minimum value from a list — all clean, modern, and interview-ready 👇 🧩 Sample Data List<Integer> myList = Arrays.asList(10, 15, 8, 49, 25, 98, 98, 32, 15); 🔥 Find Maximum Value — 10 Approaches List<Integer> myList = Arrays.asList(10,15,8,49,25,98,98,32,15); 1️⃣ Using instance comparator (compareTo on elements) myList.stream().max(Integer::compareTo).get(); 2️⃣ Using static comparator (Integer.compare) myList.stream().max(Integer::compare).get(); 3️⃣ Using IntStream for primitive comparison myList.stream().mapToInt(Integer::intValue).max().getAsInt(); 4️⃣ Using reduce() with Integer::max myList.stream().reduce(Integer::max).get(); 5️⃣ Using Collectors.summarizingInt() for all stats myList.stream().collect(Collectors.summarizingInt(i -> i)).getMax(); 6️⃣ Using Comparator.comparingInt() (good for objects too) myList.stream().max(Comparator.comparingInt(Integer::intValue)).get(); 7️⃣ Using Comparator.naturalOrder() for clean syntax myList.stream().max(Comparator.naturalOrder()).get(); 8️⃣ Using Comparable::compareTo (generic Comparable) myList.stream().max(Comparable::compareTo).get(); 9️⃣ Using custom lambda comparator (manual compare logic) myList.stream().max((a,b) -> a>b ? 1 : (a<b ? -1 : 0)).get(); 🔟 Using summaryStatistics() for one-line numeric max myList.stream().mapToInt(Integer::intValue).summaryStatistics().getMax(); 🕚 Using sorted() + skip() to pick last element myList.stream().sorted().skip(myList.size()-1).findFirst().get(); 🌙 Same Approaches for Find Minimum Value List<Integer> myList = Arrays.asList(10, 15, 8, 49, 25, 98, 98, 32, 15); 1️⃣ myList.stream().min(Integer::compareTo).get(); 2️⃣ myList.stream().min(Integer::compare).get(); 3️⃣ myList.stream().mapToInt(Integer::intValue).min().getAsInt(); 4️⃣ myList.stream().reduce(Integer::min).get(); 5️⃣ myList.stream().collect(Collectors.summarizingInt(i -> i)).getMin(); 6️⃣ myList.stream().min(Comparator.comparingInt(Integer::intValue)).get(); 7️⃣ myList.stream().min(Comparator.naturalOrder()).get(); 8️⃣ myList.stream().min(Comparable::compareTo).get(); 9️⃣ myList.stream().min((a, b) -> a > b ? 1 : (a < b ? -1 : 0)).get(); 🔟 myList.stream().mapToInt(Integer::intValue).summaryStatistics().getMin(); 🕚 myList.stream().sorted().findFirst().get(); 💡 Quick Summary for Efficiency 🧠 For numeric lists → mapToInt().max() or summaryStatistics() 🚀 For objects → Comparator.comparing() 📊 For analytics → Collectors.summarizingInt() 💪 For readability → reduce() or naturalOrder() ⚙️ For demos → sorted().skip() (less efficient) 👉 Follow me for more Java 8, Streams, and interview-ready code tips! 🔖 #Java #Java8 #Streams #CodingTips #FunctionalProgramming #InterviewPreparation #CleanCode #Developers #LinkedInLearning #CodeNewbie
"10+ Java 8 Stream Methods for Max/Min Values"
More Relevant Posts
-
🚀 𝗠𝗮𝘀𝘁𝗲𝗿𝗶𝗻𝗴 𝗝𝗮𝘃𝗮 𝗠𝗮𝗽 𝗜𝗻𝘁𝗲𝗿𝗳𝗮𝗰𝗲: 𝗛𝗮𝘀𝗵𝗠𝗮𝗽 𝘃𝘀 𝗟𝗶𝗻𝗸𝗲𝗱𝗛𝗮𝘀𝗵𝗠𝗮𝗽 𝘃𝘀 𝗧𝗿𝗲𝗲𝗠𝗮𝗽 𝘃𝘀 𝗛𝗮𝘀𝗵𝘁𝗮𝗯𝗹𝗲 If you’ve ever worked with key-value data in Java, the Map Interface is your go-to toolkit. It maps unique keys to specific values — just like storing names and phone numbers in your contacts list 📱. 𝗛𝗲𝗿𝗲’𝘀 𝗮 𝗾𝘂𝗶𝗰𝗸 𝗯𝗿𝗲𝗮𝗸𝗱𝗼𝘄𝗻: 🔹 𝗛𝗮𝘀𝗵𝗠𝗮𝗽: 𝘍𝘢𝘴𝘵𝘦𝘴𝘵, 𝘶𝘯𝘰𝘳𝘥𝘦𝘳𝘦𝘥, 𝘢𝘭𝘭𝘰𝘸𝘴 𝘰𝘯𝘦 𝘯𝘶𝘭𝘭 𝘬𝘦𝘺 — 𝘱𝘦𝘳𝘧𝘦𝘤𝘵 𝘧𝘰𝘳 𝘯𝘰𝘯-𝘵𝘩𝘳𝘦𝘢𝘥𝘦𝘥 𝘢𝘱𝘱𝘭𝘪𝘤𝘢𝘵𝘪𝘰𝘯𝘴. 🔹 𝗟𝗶𝗻𝗸𝗲𝗱𝗛𝗮𝘀𝗵𝗠𝗮𝗽: 𝘔𝘢𝘪𝘯𝘵𝘢𝘪𝘯𝘴 𝘪𝘯𝘴𝘦𝘳𝘵𝘪𝘰𝘯 𝘰𝘳𝘥𝘦𝘳 — 𝘨𝘳𝘦𝘢𝘵 𝘸𝘩𝘦𝘯 𝘰𝘳𝘥𝘦𝘳 𝘮𝘢𝘵𝘵𝘦𝘳𝘴. 🔹 𝗧𝗿𝗲𝗲𝗠𝗮𝗽: 𝘚𝘵𝘰𝘳𝘦𝘴 𝘬𝘦𝘺𝘴 𝘪𝘯 𝘴𝘰𝘳𝘵𝘦𝘥 (𝘢𝘴𝘤𝘦𝘯𝘥𝘪𝘯𝘨) 𝘰𝘳𝘥𝘦𝘳 — 𝘪𝘥𝘦𝘢𝘭 𝘧𝘰𝘳 𝘰𝘳𝘥𝘦𝘳𝘦𝘥 𝘥𝘢𝘵𝘢 𝘰𝘳 𝘳𝘢𝘯𝘨𝘦 𝘲𝘶𝘦𝘳𝘪𝘦𝘴. 🔹 𝗛𝗮𝘀𝗵𝘁𝗮𝗯𝗹𝗲: 𝘛𝘩𝘳𝘦𝘢𝘥-𝘴𝘢𝘧𝘦 𝘣𝘶𝘵 𝘰𝘭𝘥-𝘴𝘤𝘩𝘰𝘰𝘭 — 𝘳𝘦𝘱𝘭𝘢𝘤𝘦𝘥 𝘮𝘰𝘴𝘵𝘭𝘺 𝘣𝘺 𝘊𝘰𝘯𝘤𝘶𝘳𝘳𝘦𝘯𝘵𝘏𝘢𝘴𝘩𝘔𝘢𝘱. 𝗘𝘅𝗮𝗺𝗽𝗹𝗲: import java.util.*; public class MapExample { public static void main(String[] args) { // 𝟭️⃣ 𝗛𝗮𝘀𝗵𝗠𝗮𝗽 - 𝗨𝗻𝗼𝗿𝗱𝗲𝗿𝗲𝗱, 𝗮𝗹𝗹𝗼𝘄𝘀 𝗼𝗻𝗲 𝗻𝘂𝗹𝗹 𝗸𝗲𝘆 Map<Integer, String> hashMap = new HashMap<>(); hashMap.put(3, "Sachin"); hashMap.put(1, "Amit"); hashMap.put(2, "Ravi"); hashMap.put(null, "Unknown"); // Allowed System.out.println("HashMap: " + hashMap); // 𝟮️⃣ 𝗟𝗶𝗻𝗸𝗲𝗱𝗛𝗮𝘀𝗵𝗠𝗮𝗽 - 𝗠𝗮𝗶𝗻𝘁𝗮𝗶𝗻𝘀 𝗶𝗻𝘀𝗲𝗿𝘁𝗶𝗼𝗻 𝗼𝗿𝗱𝗲𝗿 Map<Integer, String> linkedHashMap = new LinkedHashMap<>(); linkedHashMap.put(3, "Sachin"); linkedHashMap.put(1, "Amit"); linkedHashMap.put(2, "Ravi"); System.out.println("LinkedHashMap: " + linkedHashMap); // 𝟯️⃣ 𝗧𝗿𝗲𝗲𝗠𝗮𝗽 - 𝗦𝗼𝗿𝘁𝗲𝗱 𝗯𝘆 𝗸𝗲𝘆, 𝗻𝗼 𝗻𝘂𝗹𝗹 𝗮𝗹𝗹𝗼𝘄𝗲𝗱 Map<Integer, String> treeMap = new TreeMap<>(); treeMap.put(3, "Sachin"); treeMap.put(1, "Amit"); treeMap.put(2, "Ravi"); System.out.println("TreeMap: " + treeMap); // 𝟰️⃣ 𝗛𝗮𝘀𝗵𝘁𝗮𝗯𝗹𝗲 - 𝗧𝗵𝗿𝗲𝗮𝗱-𝘀𝗮𝗳𝗲 𝗯𝘂𝘁 𝗻𝗼 𝗻𝘂𝗹𝗹 𝗮𝗹𝗹𝗼𝘄𝗲𝗱 Map<Integer, String> hashtable = new Hashtable<>(); hashtable.put(3, "Sachin"); hashtable.put(1, "Amit"); hashtable.put(2, "Ravi"); System.out.println("Hashtable: " + hashtable); // 🔍 𝗜𝘁𝗲𝗿𝗮𝘁𝗶𝗻𝗴 𝗼𝘃𝗲𝗿 𝗮 𝗠𝗮𝗽 for (Map.Entry<Integer, String> entry : hashMap.entrySet()) { System.out.println(entry.getKey() + " -> " + entry.getValue()); } } } 💡 𝗧𝗶𝗽: When you hear “𝗳𝗮𝘀𝘁 𝗹𝗼𝗼𝗸𝘂𝗽”, think HashMap. When you need 𝗼𝗿𝗱𝗲𝗿, think LinkedHashMap or TreeMap. When you need 𝘁𝗵𝗿𝗲𝗮𝗱 𝘀𝗮𝗳𝗲𝘁𝘆, go for ConcurrentHashMap. Understanding these differences helps you write cleaner, faster, and more scalable code 💪 #Java #HashMap #CollectionsFramework #LinkedHashMap #TreeMap #JavaInterviewPrep
To view or add a comment, sign in
-
🚀 Fixed a Logical Bug in “Contains Duplicate II” (Sliding Window Problem in Java) Today I revisited one of the seemingly simple problems — “Contains Duplicate II” — and realized how small syntax choices can completely change logic flow 😅 At first, I wrote the code using a mix of C++ and Java syntax, which caused compilation and logical issues. But while debugging, I learned some key lessons that made my solution cleaner, faster, and interview-ready 💪 🧩 The Problem Given an integer array nums and an integer k, return true if there are two distinct indices i and j such that: nums[i] == nums[j] && |i - j| <= k ⚙️ My Fixed Java Code import java.util.HashSet; class Solution { public boolean containsNearbyDuplicate(int[] nums, int k) { HashSet<Integer> set = new HashSet<>(); int i = 0; int j = 0; int n = nums.length; while (j < n) { if (Math.abs(j - i) > k) { set.remove(nums[i]); i++; } if (set.contains(nums[j])) { return true; } set.add(nums[j]); j++; } return false; } } ❌ Mistakes I Made Initially 1️⃣ Used set.get() and set.end — which belong to C++, not Java. ✅ Fixed by using set.contains(nums[j]). 2️⃣ Didn’t maintain a proper sliding window size. ✅ Simplified with if (Math.abs(j - i) > k) to ensure the window never exceeds k elements. 3️⃣ Didn’t clearly understand the window logic — that we remove older elements as we move forward. ✅ Learned to visualize the window as a moving frame over the array. 4️⃣ Overcomplicated the logic. ✅ Cleaned it up using a simple while loop and HashSet. 🧠 What I Learned Clean, minimal code > fancy syntax. Always check for language-specific methods — C++ vs Java can trick you! The sliding window technique isn’t about moving two pointers randomly — it’s about maintaining constraints efficiently. Debugging teaches more than success on the first try. 🎯 Targeting Product-Based & EdTech Companies As part of my SDE preparation for product-based and EdTech companies like FloBiz, Scaler, Razorpay, Unacademy, and Swiggy, I’m focusing on building strong fundamentals — not just solving problems, but deeply understanding why they work. 💬 Final Thought Every “wrong submission” is just a lesson wrapped in logic. Keep coding, keep debugging, and every small improvement compounds over time 💻🔥 Masai Prepleaf by Masai Newton School PhonePe Paytm Paytm Payments Bank Razorpay Razor Group PayU #Java #DSA #ProblemSolving #LeetCode #LearningInPublic #SoftwareDevelopment #ProductBasedPreparation #CodeWithDilsah #EdTech #FrontendDeveloper #FloBiz
To view or add a comment, sign in
-
-
Java ke atomic level ke secrets! 🔥 --- Post 1: Java ka "Multi-Release JAR" ka hidden feature!🤯 ```java // Java 8 version - base code public class TimeUtils { public static String getTime() { return "Legacy time: " + new Date(); } } // Java 11 version - META-INF/versions/11/TimeUtils.java public class TimeUtils { public static String getTime() { return "Modern time: " + Instant.now(); } } ``` Secret: Ek hi JAR mein multiple Java versions ke liye alag-alag class files ho sakti hain!💀 --- Post 2: Java ka "ConstantDynamic" - invokedynamic for constants!🔥 ```java public class ConstantDynamic { // Java 11+ mein constants bhi dynamically resolve ho sakte hain public static final String DYNAMIC_CONSTANT = ConstantDescs.of("Dynamically resolved constant"); // Bytecode level par invokedynamic use karta hai // instead of constant pool entry! } ``` Internal Magic: · Traditional: Constant Pool → LDC instruction · New: ConstantDynamic → invokedynamic instruction · Dynamic constant resolution at runtime! 💡 --- Post 3: Java ka "Vector API" - SIMD operations ka raaz!🚀 ```java import jdk.incubator.vector.*; public class VectorMagic { public static void main(String[] args) { IntVector a = IntVector.fromArray(IntVector.SPECIES_256, new int[]{1,2,3,4,5,6,7,8}, 0); IntVector b = IntVector.fromArray(IntVector.SPECIES_256, new int[]{8,7,6,5,4,3,2,1}, 0); IntVector result = a.add(b); // ✅ 8 operations ek saath! // CPU level par SIMD instructions use karta hai } } ``` Performance: 10x faster for mathematical operations!💪 --- Post 4: Java ka "Heap Allocation" ka hidden alternative!🔮 ```java import java.lang.foreign.*; public class OffHeapMagic { public static void main(String[] args) { // Heap se bahar memory allocate karo! try (Arena arena = Arena.ofConfined()) { MemorySegment segment = arena.allocate(100); // Direct OS memory access - no GC overhead! segment.set(ValueLayout.JAVA_INT, 0, 42); int value = segment.get(ValueLayout.JAVA_INT, 0); } } } ``` Benefits: · Zero GC pressure · Direct memory access · C-like performance 💀 --- Bhai, yeh features toh aane wali Java generations ke liye hain! 😎
To view or add a comment, sign in
-
Quick Java 8 Streams Refresh — From Revisiting to Refining: Sometimes, going back to the basics helps you rediscover how powerful simple concepts can be. I recently took some time to refresh my Java 8 Stream skills I’ve attached the complete Java file — hoping it can serve as a handy reference for anyone revisiting Streams or learning them in depth. Here’s what’s inside. 🔹 Grouping and aggregation 🔹 Calculating totals using both Collectors.summingLong() and reduce() 🔹 Word and character frequency analysis 🔹 Merging and transforming multiple lists into one stream 🔹 Detecting duplicates, unique elements, and even the second-highest transaction 🔹 Sorting complex objects with Comparator.comparing() 🔹 Reversing words, removing nulls, partitioning data, and more Each snippet reminded me how Streams simplify Java code — making it more declarative, expressive, and concise. Here’s a small example ________________________________________________________________________ // Find second highest credit transaction List<Transaction> transactions2 = new ArrayList<>(); transactions2.add(new Transaction(transactionType.CREDIT, 10)); transactions2.add(new Transaction(transactionType.CREDIT, 50)); transactions2.add(new Transaction(transactionType.DEBIT, 100)); transactions2.add(new Transaction(transactionType.DEBIT, 20)); transactions2.add(new Transaction(transactionType.CREDIT, 30)); Transaction secondHighest = transactions2.stream() .filter(t -> t.getType() == transactionType.CREDIT) .sorted(Comparator.comparingInt(Transaction::getAmount).reversed()) .skip(1) .findFirst() .get(); System.out.println(secondHighest); ________________________________________________________________________ Full code attached below — feel free to explore and reuse! Let’s keep learning, refining, and sharing knowledge together. #Java #Java8 #Streams #FunctionalProgramming #CleanCode #CodingPractice #DeveloperCommunity #LearningInPublic
To view or add a comment, sign in
-
☕💻 JAVA THREADS CHEAT SHEET 🔹 🧠 What is a Thread? 👉 The smallest unit of execution in a process. Each thread runs independently but shares memory & resources with others. 🧩 Enables multitasking and parallel execution. 🔹 ⚙️ What is a Process? 👉 An executing instance of a program. Each process has its own memory space and can run multiple threads. 🧵 Types of Threads 👤 1️⃣ User Threads ✅ Created by users or apps. ✅ JVM waits for them before exit. 💡 Example: Thread t = new Thread(() -> System.out.println("User Thread")); t.start(); 👻 2️⃣ Daemon Threads ⚙️ Background threads (e.g., Garbage Collector). ❌ JVM doesn’t wait for them. 💡 Example: Thread d = new Thread(() -> {}); d.setDaemon(true); d.start(); 🚀 Creating Threads 🔸 Extending Thread: class MyThread extends Thread { public void run(){ System.out.println("Running..."); } } new MyThread().start(); 🔸 Implementing Runnable: new Thread(() -> System.out.println("Runnable running...")).start(); 🔄 Thread Lifecycle 🧩 NEW → RUNNABLE → RUNNING → WAITING/BLOCKED → TERMINATED 🕹️ Common Thread Methods 🧩 Method ⚡ Use start() Start a thread run() Thread logic sleep(ms) Pause execution join() Wait for thread interrupt() Interrupt thread setDaemon(true) Make daemon thread 🔒 Synchronization Prevents race conditions when multiple threads share data. synchronized void increment() { count++; } 💬 Thread Communication Use wait(), notify(), and notifyAll() for coordination. 🧠 Must be called inside a synchronized block. ⚡ Executor Framework (Thread Pooling) Efficient thread reuse for better performance. ExecutorService ex = Executors.newFixedThreadPool(3); ex.submit(() -> System.out.println("Task executed")); ex.shutdown(); 🏁 Pro Tips ✅ Prefer Runnable / ExecutorService ✅ Handle InterruptedException ✅ Avoid deprecated methods (stop(), suspend()) ✅ Use java.util.concurrent for safe multithreading 📢 Boost Your Skills 🚀 #Java #Threads #Multithreading #Concurrency #JavaDeveloper #JavaInterview #JavaCoding #JavaProgrammer #CodeNewbie #ProgrammingTips #DeveloperCommunity #CodingLife #LearnJava #JavaCheatSheet #ThreadPool #TechInterview #SoftwareEngineer #CodeWithMe #JavaExperts #BackendDeveloper #JavaLearning #JavaBasics #OOP #CodeDaily #CodingJourney #DevCommunity #JavaLovers #TechCareers #CodeSmarter #100DaysOfCode
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
-
🚀 𝗨𝗻𝗱𝗲𝗿𝘀𝘁𝗮𝗻𝗱𝗶𝗻𝗴 𝘁𝗵𝗲 𝗝𝗮𝘃𝗮 𝗟𝗶𝘀𝘁 𝗜𝗻𝘁𝗲𝗿𝗳𝗮𝗰𝗲 — 𝗧𝗵𝗲 𝗛𝗲𝗮𝗿𝘁 𝗼𝗳 𝗢𝗿𝗱𝗲𝗿𝗲𝗱 𝗖𝗼𝗹𝗹𝗲𝗰𝘁𝗶𝗼𝗻𝘀 In Java’s 𝗖𝗼𝗹𝗹𝗲𝗰𝘁𝗶𝗼𝗻 𝗙𝗿𝗮𝗺𝗲𝘄𝗼𝗿𝗸, the List interface represents an ordered, index-based collection that allows duplicate elements. It’s like your digital to-do list — you can add, remove, or access any task by its position. 𝗞𝗲𝘆 𝗶𝗺𝗽𝗹𝗲𝗺𝗲𝗻𝘁𝗮𝘁𝗶𝗼𝗻𝘀: 𝗔𝗿𝗿𝗮𝘆𝗟𝗶𝘀𝘁 → 𝘥𝘺𝘯𝘢𝘮𝘪𝘤 𝘢𝘳𝘳𝘢𝘺𝘴, 𝘨𝘳𝘦𝘢𝘵 𝘧𝘰𝘳 𝘧𝘢𝘴𝘵 𝘳𝘢𝘯𝘥𝘰𝘮 𝘢𝘤𝘤𝘦𝘴𝘴 𝗟𝗶𝗻𝗸𝗲𝗱𝗟𝗶𝘀𝘁 → 𝘱𝘦𝘳𝘧𝘦𝘤𝘵 𝘧𝘰𝘳 𝘧𝘳𝘦𝘲𝘶𝘦𝘯𝘵 𝘪𝘯𝘴𝘦𝘳𝘵𝘪𝘰𝘯𝘴 𝘢𝘯𝘥 𝘥𝘦𝘭𝘦𝘵𝘪𝘰𝘯𝘴 𝗩𝗲𝗰𝘁𝗼𝗿 → 𝘭𝘦𝘨𝘢𝘤𝘺 𝘵𝘩𝘳𝘦𝘢𝘥-𝘴𝘢𝘧𝘦 𝘷𝘦𝘳𝘴𝘪𝘰𝘯 (𝘯𝘰𝘵 𝘤𝘰𝘮𝘮𝘰𝘯𝘭𝘺 𝘶𝘴𝘦𝘥 𝘵𝘰𝘥𝘢𝘺) 𝗦𝘁𝗮𝗰𝗸 → 𝘤𝘭𝘢𝘴𝘴𝘪𝘤 𝘓𝘐𝘍𝘖 𝘥𝘢𝘵𝘢 𝘴𝘵𝘳𝘶𝘤𝘵𝘶𝘳𝘦 𝘣𝘶𝘪𝘭𝘵 𝘰𝘯 𝘝𝘦𝘤𝘵𝘰𝘳 Each serves a specific purpose depending on whether you value speed, memory efficiency, or thread safety. 𝗘𝘅𝗮𝗺𝗽𝗹𝗲 𝗖𝗼𝗱𝗲 import java.util.*; public class ListExamples { public static void main(String[] args) { // 𝗔𝗿𝗿𝗮𝘆𝗟𝗶𝘀𝘁 𝗘𝘅𝗮𝗺𝗽𝗹𝗲 List<String> arrayList = new ArrayList<>(); arrayList.add("Java"); arrayList.add("Python"); arrayList.add("C++"); arrayList.add("Python"); // duplicates allowed System.out.println("ArrayList: " + arrayList); // 𝗟𝗶𝗻𝗸𝗲𝗱𝗟𝗶𝘀𝘁 𝗘𝘅𝗮𝗺𝗽𝗹𝗲 List<String> linkedList = new LinkedList<>(); linkedList.add("Spring"); linkedList.add("Hibernate"); linkedList.addFirst("Java EE"); System.out.println("LinkedList: " + linkedList); // 𝗩𝗲𝗰𝘁𝗼𝗿 𝗘𝘅𝗮𝗺𝗽𝗹𝗲 Vector<Integer> vector = new Vector<>(); vector.add(10); vector.add(20); vector.add(30); System.out.println("Vector: " + vector); // 𝗦𝘁𝗮𝗰𝗸 𝗘𝘅𝗮𝗺𝗽𝗹𝗲 Stack<String> stack = new Stack<>(); stack.push("Apple"); stack.push("Banana"); stack.push("Cherry"); System.out.println("Stack before pop: " + stack); stack.pop(); System.out.println("Stack after pop: " + stack); } } 𝗢𝘂𝘁𝗽𝘂𝘁: 𝘈𝘳𝘳𝘢𝘺𝘓𝘪𝘴𝘵: [𝘑𝘢𝘷𝘢, 𝘗𝘺𝘵𝘩𝘰𝘯, 𝘊++, 𝘗𝘺𝘵𝘩𝘰𝘯] 𝘓𝘪𝘯𝘬𝘦𝘥𝘓𝘪𝘴𝘵: [𝘑𝘢𝘷𝘢 𝘌𝘌, 𝘚𝘱𝘳𝘪𝘯𝘨, 𝘏𝘪𝘣𝘦𝘳𝘯𝘢𝘵𝘦] 𝘝𝘦𝘤𝘵𝘰𝘳: [10, 20, 30] 𝘚𝘵𝘢𝘤𝘬 𝘣𝘦𝘧𝘰𝘳𝘦 𝘱𝘰𝘱: [𝘈𝘱𝘱𝘭𝘦, 𝘉𝘢𝘯𝘢𝘯𝘢, 𝘊𝘩𝘦𝘳𝘳𝘺] 𝘚𝘵𝘢𝘤𝘬 𝘢𝘧𝘵𝘦𝘳 𝘱𝘰𝘱: [𝘈𝘱𝘱𝘭𝘦, 𝘉𝘢𝘯𝘢𝘯𝘢] 💡 In real-world applications, Lists manage user records, logs, orders, and much more. Choosing the right implementation can make a big difference in performance. #Java #OOP #CollectionFramework #ArrayList #LinkedList #Stack #Vector #JavaDeveloper
To view or add a comment, sign in
-
🚀 Today I Deepened My Understanding of Strings in Java Today, I explored the differences between String, StringBuffer, and StringBuilder classes in Java — focusing on mutability, performance, and thread safety. 🔹 1️⃣ String (Immutable) Strings in Java are immutable — once created, they cannot be modified. Every modification creates a new String object. Thread-safe: Yes (due to immutability) Performance: Slower for frequent modifications Common Methods: length(), charAt(), substring(), toUpperCase(), toLowerCase(), equals(), equalsIgnoreCase(), indexOf(), startsWith(), endsWith(), replace(), split() 🔹 2️⃣ StringBuffer (Mutable & Thread-Safe) Used when frequent string modifications are required. Mutable: Can be modified without creating new objects. Thread-safe: Yes (methods are synchronized) Performance: Slower compared to StringBuilder due to synchronization overhead. Common Methods: append(), insert(), replace(), delete(), reverse(), capacity(), ensureCapacity(), setCharAt() 🔹 3️⃣ StringBuilder (Mutable & Non-Thread-Safe) Similar to StringBuffer, but not synchronized, hence faster. Thread-safe: No Best for: Single-threaded environments. Performance: Faster than StringBuffer Methods: Same as StringBuffer 🔹 4️⃣ Conversion Between Types Immutable → Mutable: StringBuffer sb = new StringBuffer(str); StringBuilder sbl = new StringBuilder(str); Mutable → Immutable: String str = sb.toString(); 🔹 5️⃣ String Tokenization I also explored string splitting techniques in Java: split() Method: Modern and efficient; uses regex. StringTokenizer Class: Older and slower; uses more memory. Example: String s = "Java is powerful"; String[] parts = s.split(" "); // Preferred modern approach import java.util.StringTokenizer; // StringTokenizer StringTokenizer st = new StringTokenizer("Java is powerful"); while (st.hasMoreTokens()) { System.out.println(st.nextToken()); } 💡 Final Insight Understanding how Java handles string operations — from immutability to synchronization — is crucial for writing efficient and thread-safe code. #Java #LearningJourney #SoftwareDevelopment #StringHandling #CodingInJava #JavaDeveloper
To view or add a comment, sign in
-
-
Java ke woh secrets jo documentation mein bhi nahi hain! 🔥 --- Post 1: Java Compiler ka "Negative Array Size" bug!🤯 ```java public class NegativeArray { public static void main(String[] args) { try { int[] arr = new int[-5]; // ❌ Negative size } catch (NegativeArraySizeException e) { // Ye exception JVM ke internal memory allocation se aati hai // Java specification ke according, yeh error compulsory hai! } } } ``` Secret: Java specification page 329: "Array creation with negative size must throw NegativeArraySizeException" - ye rule JVM implementers ko follow karna compulsory hai! 💀 --- Post 2: Java ka "Floating-Point Non-Associativity" paradox!🔥 ```java public class FloatingParadox { public static void main(String[] args) { double a = 1.0e308; // Very large number double b = -1.0e308; // Very large negative double c = 1.0; double result1 = (a + b) + c; // (0) + 1 = 1 double result2 = a + (b + c); // Infinity + (-Infinity) = NaN System.out.println(result1); // 1.0 System.out.println(result2); // NaN } } ``` Mathematical Paradox: Java floating-point arithmetic associative nahi hai! IEEE 754 standard ka hidden rule! 💡 --- Post 3: Java ka "Class File Magic Number" ka raaz!🚀 ```java // Har .class file ke start mein ye 4 bytes hote hain: // CA FE BA BE - "Coffee Baby"! // Ye Java creators ne randomly choose kiya tha 1995 mein! public class MagicNumber { public static void main(String[] args) throws Exception { byte[] classBytes = java.nio.file.Files.readAllBytes( java.nio.file.Paths.get("MagicNumber.class") ); // First 4 bytes check karo System.out.printf("%02X %02X %02X %02X", classBytes[0], classBytes[1], classBytes[2], classBytes[3]); // Output: CA FE BA BE } } ``` Historical Secret: James Gosling team ne ye magic number randomly rakha tha! 💪 --- Post 4: Java ka "Null Type" ka compiler-level existence!🔮 ```java public class NullType { public static void main(String[] args) { // Java compiler internally null ka ek special type maintain karta hai // called "the null type" - jiska koi name nahi hota! String s = null; Integer i = null; // Compiler null ko kisi bhi reference type assign kar sakta hai // kyunki uska apna alag "null type" hai! } } ``` Language Theory: Java Language Specification §4.1: "There is also a special null type, the type of the expression null" - ye type sirf compiler internally use karta hai! 💀
To view or add a comment, sign in
-
💡 Part 2 — String Comparison, Concatenation & Immutability in Java In the previous post, we discussed how Strings, SCP, and intern() work in Java. Now let’s explore how they behave when we compare or modify them 👇 🔹 1️⃣ == vs .equals() String s1 = "Java"; String s2 = "Java"; System.out.println(s1 == s2); // true ✅ System.out.println(s1.equals(s2)); // true ✅ 👉 == → compares references (memory addresses) 👉 .equals() → compares values (content) If both strings come from the String Constant Pool (SCP), == can return true. But when we create new objects using new, they live in heap, so: String s1 = new String("Java"); String s2 = "Java"; System.out.println(s1 == s2); // false ❌ (different memory) 🔹 2️⃣ Compile-time vs Runtime Concatenation String s1 = "Ja" + "va"; String s2 = "Java"; System.out.println(s1 == s2); // true ✅ 👉 Concatenation of string literals happens at compile-time, so both refer to the same object in SCP. But when concatenation happens at runtime, a new object is created: String part = "Ja"; String s3 = part + "va"; System.out.println(s2 == s3); // false ❌ 🔹 3️⃣ Immutability of Strings String s = "abc"; s.concat("xyz"); System.out.println(s); // abc ❌ (unchanged) Strings are immutable — every modification creates a new object. To reflect the change, you must reassign: s = s.concat("xyz"); System.out.println(s); // abcxyz ✅ 🔹 4️⃣ Using intern() for Optimization If you want to make sure your heap string refers to SCP: String s1 = new String("Java"); String s2 = s1.intern(); System.out.println("Java" == s2); // true ✅ 👉 intern() makes your string memory-efficient and reusable. 🧠 Quick Recap ✅ == → reference check ✅ .equals() → content check ✅ Compile-time concat → stored in SCP ✅ Runtime concat → new object in heap ✅ Strings are immutable ✅ Use intern() for SCP optimization #Java #String #Coding #JavaDeveloper
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