🚀 Day 3 of Java Series 👉 Find common elements between two lists using Streams import java.util.*; import java.util.stream.*; public class CommonElementsExample { public static void main(String[] args) { List<Integer> list1 = List.of(10, 20, 30, 40, 50); List<Integer> list2 = List.of(30, 40, 60, 70); Set<Integer> set2 = new HashSet<>(list2); List<Integer> common = list1.stream() .filter(set2::contains) .toList(); System.out.println(common); // [30, 40] } } 💡 What’s happening here? ✔ Convert one list into a HashSet → O(1) lookup ✔ Stream through list1 ✔ Filter only elements present in list2 ✔ Collect result into a list ⚡ Key Insight: Using List.contains() leads to O(n²) complexity Using HashSet reduces it to O(n + m) 🧠 Interview Tip: Always optimize lookups using HashSet when dealing with search operations 📌 Output: [30, 40] ❓Can you think of a way to handle duplicates in both lists? #Java #Streams #CodingInterview #Developers #JavaDeveloper #Learning #Tech
Java Streams: Find Common Elements in Two Lists
More Relevant Posts
-
🧠 Java MCQ – Answer Explanation Question Recap Java List<String> list = new ArrayList<>(); list.add("A"); list.add("B"); list.add("A"); System.out.println(list.size()); Correct Answer: C) 3 ✅ Step-by-Step Explanation List in Java allows duplicate elements. ArrayList implements the List interface. When elements are added to an ArrayList, they are stored in insertion order. There is no restriction on adding the same value multiple times. ▶ Execution Flow list.add("A"); → List becomes: ["A"] list.add("B"); → List becomes: ["A", "B"] list.add("A"); → List becomes: ["A", "B", "A"] Even though "A" is added twice, it is accepted. 📌 Final Point list.size() returns the total number of elements present, including duplicates. So, total elements = 3 Output: 3 💡 Key Concept to Remember List → allows duplicates Set → does NOT allow duplicates ArrayList → preserves insertion order size() → counts all elements including duplicates #JavaMCQ #CodingMCQ #InterviewPreparation #MNCInterview #CodeAnalysis #ConceptClarity #JavaLearning #ServletJSP #JDBC #OracleDB #DeveloperMindset #PracticeCoding
To view or add a comment, sign in
-
-
🚀 Java Streams Interview Question Given a list of integers, remove duplicates and return a sorted list using Stream API. import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class Main { public static void main(String[] args) { List<Integer> numbers = Arrays.asList(5, 3, 8, 1, 3, 5, 9, 2, 8); List<Integer> sortedUniqueNumbers = numbers.stream() .distinct() .sorted() .collect(Collectors.toList()); System.out.println(sortedUniqueNumbers); } } Output: [1, 2, 3, 5, 8, 9] 🔹 distinct() removes duplicate elements 🔹 sorted() arranges the elements in ascending order 🔹 collect(Collectors.toList()) converts the stream back to a list #Java #JavaStreams #CodingInterview #Programming #Developers #SoftwareEngineering #BackendDevelopment
To view or add a comment, sign in
-
💡 Handling Null Values in Java using Optional (Java 8+) One of the most common problems in Java applications is the dreaded NullPointerException 😓 To address this, Java introduced Optional, which helps us write cleaner and safer code by explicitly handling the absence of values. Let’s understand this with a simple example 👇 🔴 Without Optional (Risky Approach) public String getUserById(int id) { if (id == 1) { return "Pavitra"; } else { return null; // ❌ Risk of NullPointerException } } Usage: String name = obj.getUserById(2); if (name != null) { System.out.println(name.toUpperCase()); } else { System.out.println("Name not found"); } 🟢 With Optional (Safe & Modern Approach) import java.util.Optional; public Optional<String> getUserNameById(int id) { if (id == 1) { return Optional.of("Vijay"); // value present } else { return Optional.empty(); // no value } } Usage: Optional<String> name = obj.getUserNameById(2); // Method 1 if (name.isPresent()) { System.out.println(name.get()); } else { System.out.println("Name not found"); } // Method 2 System.out.println(name.orElse("Default Name")); // Method 3 obj.getUserNameById(1).ifPresent(System.out::println); 🔍 Key Takeaways: ✔ Avoid returning null directly ✔ Use Optional to represent absence of value ✔ Improves code readability & safety ✔ Reduces chances of NullPointerException 🎯 Interview Tip: 👉 “Optional makes null handling explicit and encourages better coding practices.” Are you using Optional in your projects, or still relying on null checks? Let’s discuss 👇 #Java #CoreJava #Java8 #Optional #Programming #Developers #CodingTips #JavaLearning
To view or add a comment, sign in
-
Day 9 Java Practice: Find the First Non-Repeated Character in a String While practicing Java, I worked on a classic string problem: 👉 Find the first non-repeated character in a given string. For example, in the string "swiss", the first character that does not repeat is 'w'. To solve this, I used a LinkedHashMap to store character counts while preserving insertion order. Then I iterated through the map to find the first character with count = 1. ================================================== // 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) { String s="swiss"; char[] words=s.toCharArray(); Map<Character,Integer>map=new LinkedHashMap<Character,Integer>(); for(char word:words) { map.put(word,map.getOrDefault(word,0)+1); } for(Map.Entry<Character,Integer>entry:map.entrySet()) { if(entry.getValue()==1) { System.out.println("First non-repeated character in the string is:"+entry.getKey()); break; } } } } Output:First non-repeated character in the string is:w This was a good exercise to understand: Character frequency counting Importance of insertion order using LinkedHashMap String traversal logic #AutomationTestEngineer #Selenium #Java #CodingPractice #ProblemSolving
To view or add a comment, sign in
-
-
💡 Java Interview Question How do you find the common elements from three lists in Java? Here’s a simple example: ✅ Two approaches: Using retainAll() with Set Using Java 8 Streams public class CommonElementFrom3List { public static void main(String[] args){ List<Integer> list1 = Arrays.asList(1, 2, 3, 4, 5); List<Integer> list2 = Arrays.asList(3, 4, 5, 6, 7); List<Integer> list3 = Arrays.asList(5, 6, 7, 8, 3); Set<Integer> common = new HashSet<>(list1); common.retainAll(list2); common.retainAll(list3); System.out.println(common); List<Integer> list = list1.stream() .filter(list2::contains) .filter(list3::contains) .distinct() .collect(Collectors.toList()); System.out.println(list); } } 📌 Output: [3, 5] ❓ Question for you: Which approach would you prefer in a real-world scenario and why? Also, how would you handle duplicate elements efficiently? #Java #CodingInterview #JavaDeveloper #Programming #TechLearning
To view or add a comment, sign in
-
☕ Java Interview Question 📌 Why can’t we create a generic array in Java? In Java, generic arrays are restricted because arrays and generics handle type information differently. 🔹 Key Reason: ✔ Arrays are Reified • Arrays store and check their element type at runtime ✔ Generics use Type Erasure • Generic type information is removed during compilation ✔ Type Safety Conflict • Runtime cannot verify the actual generic type inside an array 🔹 What Problem Can Occur? • It may allow invalid assignments at runtime • Can lead to ArrayStoreException or unsafe behavior 🔹 Example: • new T[10] is not allowed because T is unknown at runtime 💡 In Short: Java prevents generic array creation to maintain type safety between compile-time generics and runtime array checks. 👉For Java Course Details Visit : https://lnkd.in/gwBnvJPR . #Java #JavaInterview #Generics #TypeErasure #Programming #InterviewPreparation #CoreJava#ashokit
To view or add a comment, sign in
-
-
Most Java developers write code. Very few write good Java code🔥 Here are 10 Java tips every developer should know 👇 1. Prefer interfaces over implementation → Code to "List" not "ArrayList" 2. Use "StringBuilder" for string manipulation → Avoid creating unnecessary objects 3. Always override "equals()" and "hashCode()" together → Especially when using collections 4. Use "Optional" wisely → Avoid "NullPointerException", but don’t overuse it 5. Follow immutability where possible → Makes your code safer and thread-friendly 6. Use Streams, but don’t abuse them → Readability > fancy one-liners 7. Close resources properly → Use try-with-resources 8. Avoid hardcoding values → Use constants or config files 9. Understand JVM basics → Memory, Garbage Collection = performance impact 10. Write meaningful logs → Debugging becomes 10x easier Clean code isn't about writing more. It’s about writing smarter. Which one do you already follow? 👇 #Java #JavaDeveloper #SoftwareEngineering #BackendDevelopment #SpringBoot #CleanCode #Programming #Developers #TechTips #CodingLife
To view or add a comment, sign in
-
-
🚀 Java Streams Interview Gem: Find Duplicate Numbers in a List Working with collections is common, but identifying duplicates efficiently is a must-have skill for any Java developer 💡 Here’s how you can find duplicate numbers using Java Streams 👇 🔹 Approach: We use a Set to track elements and filter duplicates while streaming the list. 🔹 Code: import java.util.*; import java.util.stream.*; public class FindDuplicates { public static void main(String[] args) { List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 2, 5, 6, 3, 7, 1); Set<Integer> seen = new HashSet<>(); Set<Integer> duplicates = numbers.stream() .filter(n -> !seen.add(n)) .collect(Collectors.toSet()); System.out.println("Duplicate Numbers: " + duplicates); } } 🔹 Output: Duplicate Numbers: [1, 2, 3] 🔹 How it works? ✔ seen.add(n) returns false if the element is already present ✔ We filter those elements → duplicates ✔ Collect them into a Set to avoid repeated duplicates 💥 Alternative (Using Grouping): 🔥 Mastering Streams = Cleaner + More Functional Code #Java #JavaStreams #CodingInterview #Developers #Programming #Tech #100DaysOfCode
To view or add a comment, sign in
-
🚀 Java Puzzle: Why this prints "100" even after using "final"? 🤯 Looks like a bug… but it’s actually Java behavior 👇 👉 Example: final int[] arr = {1, 2, 3}; arr[0] = 100; System.out.println(arr[0]); // 100 😮 👉 Wait… "final" but still changing? 🤔 💡 Reality of "final": - "final" → reference cannot change - NOT → object data cannot change 👉 So: - ❌ "arr = new int[]{4,5,6}" → not allowed - ✅ "arr[0] = 100" → allowed --- 🔥 Now the REAL twist 😳 final StringBuilder sb = new StringBuilder("Java"); sb.append(" Developer"); System.out.println(sb); // Java Developer 😮 👉 Again changing despite "final" 🔥 Golden Rule: 👉 "final" means: - You cannot point to a new object - But you CAN modify the existing object 💡 Common misconception: 👉 Many think "final = constant" (NOT always true) 💬 Did you also think "final" makes everything immutable? #Java #JavaDeveloper #Programming #Coding #100DaysOfCode #TechTips #JavaTips #InterviewPrep #Developers #SoftwareEngineering
To view or add a comment, sign in
-
☕ Java Interview Question 📌 Explain the LinkedList class in Java In Java, LinkedList is a collection class that stores elements using a doubly linked list structure. 🔹 Key Features ✔ Maintains insertion order ✔ Allows duplicate elements ✔ Non-synchronized by default 🔹 Implementation ✔ Implements List and Deque interfaces ✔ Can be used as a list, queue, or stack 🔹 Performance ✔ Fast insertion and deletion in the middle ✔ Slower random access compared to ArrayList 🔹 Syntax • LinkedList<Type> list = new LinkedList<>(); 💡 In Short: LinkedList is best when frequent insertions and deletions are needed instead of fast indexing 🚀☕ 👉For JAVA Course Details Visit : https://lnkd.in/gwBnvJPR . #Java #LinkedList #JavaInterview #Collections #Programming #InterviewPreparation #TechSkills
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
Output will be [30,40,50]