💡 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
Yashodha Kittur’s Post
More Relevant Posts
-
☕ 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
-
-
Interview Question: What is Autoboxing and Unboxing in Java? Autoboxing and Unboxing are concepts in Java that handle the conversion between primitive data types and their corresponding wrapper classes. Autoboxing is the automatic conversion of a primitive type into its wrapper object. Unboxing is the reverse process, where a wrapper object is converted back into a primitive type. Example: int a = 10; // Autoboxing Integer obj = a; // Unboxing int b = obj; System.out.println(a + " " + obj + " " + b); 👉 Here, Java automatically converts: int → Integer (Autoboxing) Integer → int (Unboxing) Usage in Collections: import java.util.ArrayList; ArrayList<Integer> list = new ArrayList<>(); list.add(10); // Autoboxing int value = list.get(0); // Unboxing 👉 Collections store objects, so autoboxing makes it seamless to use primitives. ⚠️ Important Edge Case: Integer obj = null; int x = obj; // Throws NullPointerException 👉 During unboxing, if the wrapper object is null, it results in a runtime error. #Java #InterviewQuestions #Programming #BackendDevelopment #SoftwareEngineering
To view or add a comment, sign in
-
-
🧠 Java Interview Question 👉 How to find duplicate characters in a String? Example: Input: "programming" Output: g, r, m Simple approach using HashMap: import java.util.HashMap; public class DuplicateCharacter { public static void main(String[] args) { String str = "programming"; HashMap<Character, Integer> map = new HashMap<>(); for (char c : str.toCharArray()) { map.put(c, map.getOrDefault(c, 0) + 1); } for (char c : map.keySet()) { if (map.get(c) > 1) { System.out.println(c); } } } } 💡 Logic: Count frequency of each character and print duplicates. 👉 Have you solved this in a different way? #Java #SpringBoot #Coding #InterviewQuestions #BackendDeveloper
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
-
🚀 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
-
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 📌 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
-
-
☕ Java Interview Question 📌 What is the difference between Checked Exception and Unchecked Exception? 🔹 Checked Exception ✔ Checked at compile time ✔ Must be handled using try-catch or declared with throws ✔ Usually occurs due to external conditions beyond program control Examples: • IOException • SQLException • InterruptedException 🔹 Unchecked Exception ✔ Occurs at runtime ✔ Not mandatory to handle at compile time ✔ Usually caused by programming mistakes or invalid logic Examples: • NullPointerException • ArrayIndexOutOfBoundsException • ArithmeticException 💡 In Short: Checked exceptions are verified by the compiler, while unchecked exceptions occur during program execution ⚡ 👉For Java Course Details Visit : https://lnkd.in/gwBnvJPR . #Java #CoreJava #Exceptions #CheckedException #UncheckedException #InterviewPreparation #JavaDeveloper #TechLearning #AshokIT
To view or add a comment, sign in
-
-
Java Coding Question What will be the output of the following code? public class Test { public static void main(String[] args) { int[] arr = {1, 2, 3, 4, 5}; for (int i = 0; i < arr.length; i++) { arr[i] = arr[i] + 1; } for (int num : arr) { System.out.print(num + " "); } } } Options: A) 1 2 3 4 5 B) 2 3 4 5 6 C) 1 3 5 7 9 D) Compile-time error 👉 Comment your answer before running the code. #Java #JavaProgramming #CodingChallenge #RalithonTechnologies #JavaInterview #ProblemSolving #Developers #LinkedInPost
To view or add a comment, sign in
-
🚀 Java Basic That Many Ignore: What is String[] args in main()? 🤔 We write this every day: public static void main(String[] args) { System.out.println("Hello"); } 👉 But what exactly is args? 💡 args = Command Line Arguments It is an array of Strings passed when running your program 👉 Example: public class Test { public static void main(String[] args) { System.out.println(args[0]); } } Run this: java Test Hello 👉 Output: Hello 🤯 Important Points: args is just a variable name (you can change it) It is always an array of String It can be empty (no arguments passed) 🔥 Fun Fact: public static void main(String[] xyz) 👉 This also works! 😄 ⚠️ Be careful: System.out.println(args[0]); ❌ If no argument → ArrayIndexOutOfBoundsException 💡 Safe way: if (args.length > 0) { System.out.println(args[0]); } Small concept… but important for interviews & real-world usage 💪 #Java #Programming #Coding #JavaDeveloper #InterviewPrep #Developers
To view or add a comment, sign in
Explore related topics
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