🚀 Java Practice Problem: Mastering List Operations (Insert & Delete) Here’s a classic problem I recently worked on — perfect for students learning Java Collections and preparing for coding interviews 👇 💡 Problem Statement You are given a list of integers. You need to perform multiple queries of two types: 🔹 Insert x y → Insert value y at index x 🔹 Delete x → Delete element at index x After performing all queries, print the updated list. 🧠 Key Learning Many students try solving this using arrays ❌ But the correct approach is to use ArrayList ✅ 👉 Why? Dynamic size Easy insert & delete Cleaner and efficient code ✅ Solution Approach ✔ Read input list ✔ Loop through queries ✔ Use: list.add(index, value) for Insert list.remove(index) for Delete 💻 Java Code import java.util.*; public class Solution { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int L = scanner.nextInt(); ArrayList<Integer> list = new ArrayList<>(); for(int i = 0; i < L; i++) { list.add(scanner.nextInt()); } int Q = scanner.nextInt(); for(int i = 0; i < Q; i++) { String query = scanner.next(); if(query.equals("Insert")) { int index = scanner.nextInt(); int value = scanner.nextInt(); list.add(index, value); } else if(query.equals("Delete")) { int index = scanner.nextInt(); list.remove(index); } } for(int num : list) { System.out.print(num + " "); } } } 📌 Sample Input 5 12 0 1 78 12 2 Insert 5 23 Delete 0 📌 Output 0 1 78 12 23 🎯 Teaching Insight As a trainer, I always emphasize: 👉 Choose the right data structure before coding 👉 Understand problem pattern (CRUD operations) 👉 Focus on clean and readable code 💬 Try this problem and let me know — did you first think of arrays or ArrayList? #Java #JavaProgramming #ArrayList #CodingPractice #LearnToCode #Programming #JavaTrainer #CodingInterview #TechEducation
Mastering List Operations in Java with ArrayList
More Relevant Posts
-
Day 7 of My Java Backend Journey – Understanding Sorting in Java Today, I learned how sorting works in Java Collections — a key concept used in almost every real-world application. Why Sorting is Needed? In real projects, we often need to: - Sort students by marks - Sort products by price - Sort employees by salary Defining sorting logic is essential. Two Ways to Sort in Java: 1. Comparable (Natural sorting) 2. Comparator (Custom sorting) Comparable: - Used to define default (natural) sorting - Implemented inside the class itself - Only one default sorting can be defined - Example use: Sort students by marks (default behavior) Comparator: - Used to define custom or multiple sorting logic - Implemented separately - Allows multiple ways of sorting - Example use: Sort students by name, Sort students by marks in descending order Key Difference: | Feature | Comparable | Comparator | |----------------|---------------------|---------------------| | Package | java.lang | java.util | | Method | compareTo() | compare() | | Defined in | Same class | Separate class | | Sorting | One default | Multiple custom | Core Understanding (Interview Point): - Comparable = how an object behaves normally - Comparator = how we want to sort it now Sorting Methods in Java: - Collections.sort() → Default sorting - Collections.sort(list, comparator) → Custom sorting - list.sort(comparator) → Java 8 approach Real-world Scenario: For a Student object: - Default sort → by marks (Comparable) - Custom sort → by name or any other field (Comparator) Key Takeaways: - Sorting is widely used in real-world applications - Comparable is for default behavior - Comparator gives flexibility for multiple sorting logics - Understanding both is crucial for interviews Completed one full cycle of Java Collections — consistency matters! #Java #BackendDevelopment #JavaCollections #LearningInPublic #Freshers #30DaysOfCode
To view or add a comment, sign in
-
🚀 Java Series – Day 25 📌 Comparable vs Comparator in Java 🔹 What is it? Both Comparable and Comparator are interfaces in Java used to define the natural or custom ordering of objects. 🔹 Why do we use it? We use them to sort collections like List or Set efficiently. For example: • Sorting employees by age • Sorting products by price • Sorting students by name 🔹 How They Work Internally: 1️⃣ Comparable - Implemented inside the class itself - Method: int compareTo(Object o) - Defines natural ordering 2️⃣ Comparator - Implemented outside the class - Method: int compare(Object o1, Object o2) - Defines custom ordering 🔹 Example – Comparable: class Student implements Comparable<Student> { String name; int age; Student(String name, int age) { this.name = name; this.age = age; } @Override public int compareTo(Student s) { return this.age - s.age; // ascending order by age } @Override public String toString() { return name + " - " + age; } } List<Student> students = new ArrayList<>(); students.add(new Student("Alice", 22)); students.add(new Student("Bob", 20)); students.add(new Student("Charlie", 21)); Collections.sort(students); System.out.println(students); 🔹 Example – Comparator: class StudentAgeComparator implements Comparator<Student> { @Override public int compare(Student s1, Student s2) { return s2.age - s1.age; // descending order by age } } Collections.sort(students, new StudentAgeComparator()); System.out.println(students); 💡 Key Takeaway: - Comparable → Natural order, one way - Comparator → Custom order, multiple ways #Java #Comparable #Comparator #Collections #JavaDeveloper #Programming #BackendDevelopment
To view or add a comment, sign in
-
-
🚀 Comparable vs Comparator in Java — Stop Confusing Them! If you're preparing for Java interviews or strengthening your core concepts, understanding the difference between Comparable and Comparator is a must. Let’s break it down simply 👇 --- 🔹 Comparable (Natural Ordering) - Used to define the default sorting logic of a class - Implemented inside the same class - Uses "compareTo()" method ✅ Example: class Student implements Comparable<Student> { int marks; public int compareTo(Student s) { return this.marks - s.marks; } } 👉 Here, sorting is based on marks by default --- 🔹 Comparator (Custom Ordering) - Used to define multiple sorting logics - Implemented in a separate class or lambda - Uses "compare()" method ✅ Example: Comparator<Student> sortByName = (s1, s2) -> s1.name.compareTo(s2.name); 👉 Now you can sort by name, age, or anything! --- ⚡ Key Differences Feature| Comparable| Comparator Package| java.lang| java.util Method| compareTo()| compare() Logic| Single (default)| Multiple (custom) Modification| Inside class| Outside class --- 💡 Pro Tip: Use Comparable when you have a natural sorting order Use Comparator when you need flexibility & multiple sorting options --- 🔥 Mastering these concepts not only helps in interviews but also improves how you design scalable Java applications. #Java #DSA #Programming #CodingInterview #JavaDeveloper #Learning #Tech
To view or add a comment, sign in
-
☕ Java Core Concepts – Interview Question 📌 What is a Constructor? In Java, a Constructor is a special method used to initialize objects when they are created. 🔹 Key Features: ✔ Called automatically when an object is created ✔ Name must be same as the class name ✔ No return type (not even void) ✔ Used to initialize instance variables ✔ Can be overloaded (multiple constructors with different parameters) 🔹 Types of Constructors: • Default Constructor – No parameters • Parameterized Constructor – Accepts arguments 🔹 Example: class Student { String name; // Constructor Student(String n) { name = n; } void display() { System.out.println(name); } public static void main(String[] args) { Student s = new Student("Tharun"); s.display(); } } 💡 In Short: A constructor is used to set up an object’s initial state at the time of creation. 👉For java Course Details Visit : https://lnkd.in/gwBnvJPR . #Java #CoreJava #Constructor #JavaInterview #Programming #Coding #TechSkills
To view or add a comment, sign in
-
-
Java#P1 📌 Java Learning: How to remove duplicate characters from a string 👇 public class Remove Duplicates { public static void main(String[] args) { String str="programming"; String result=""; for (char ch : str.toCharArray()) { if (result.indexOf(ch) ==-1) { result+=ch; } } System.out.println("Original String: "+str); System.out.println("After removing duplicates: "+result); } } } 🧾 Output Original String: programming After removing duplicates: progamin 💡 indexOf() returns -1 → character not present Simple logic, but very useful in interviews. #Java #Coding #SDET #LearningInPublic
To view or add a comment, sign in
-
🚀 Understanding TreeSet in Java – Clean, Sorted & Powerful! While working with Java Collections, I explored TreeSet, a powerful implementation of the Set interface that ensures data is always sorted and unique. Here are some key insights I learned: 🔹 Sorted Order TreeSet automatically stores elements in ascending sorted order, making it ideal when ordering is important. 🔹 Traversal Mechanism It internally follows Inorder Traversal (LVR), which is why elements remain sorted. 🔹 Data Type TreeSet stores only homogeneous data, as elements must be mutually comparable. 🔹 No Duplicates Allowed Being a Set, it does not allow duplicate values. 🔹 No Null Values TreeSet does not allow null, as it relies on comparison logic. 🔹 Insertion Order Not Preserved Unlike some collections, it does not maintain insertion order. 🔹 Initial Capacity TreeSet does not define an initial capacity (internally managed). 🔹 Constructors TreeSet provides 5 different constructors for flexibility. 🔹 Internal Data Structure It is based on a Binary Search Tree (BST) (specifically a self-balancing tree like Red-Black Tree). 💡 Accessing Elements in TreeSet Since TreeSet does not support indexing, we use: ✔️ For-each loop ✔️ Iterator ✔️ Descending Iterator ❌ Not supported: Traditional for loop (index-based) ListIterator 🎯 When to Use TreeSet? Use TreeSet when you need: ✔️ Sorted data ✔️ Unique elements ✔️ Efficient searching and retrieval 📌 Mastering collections like TreeSet helps in writing cleaner and more efficient Java programs. #Java #CollectionsFramework #TreeSet #Programming #JavaDeveloper #LearningJourney TAP Academy
To view or add a comment, sign in
-
-
🚀 Java Comparator Practice – Sorting Students by CGPA Today I worked on an interesting problem that strengthens understanding of Java Comparators and object sorting. Sharing it here for learners and interview preparation 👇 📌 Problem Statement: You are given a list of student details: ID First Name CGPA 🔹 Sort the students based on: CGPA (Descending order) If CGPA is same → First Name (Alphabetical order) If both are same → ID (Ascending order) 👉 Finally, print only the first names of students in sorted order. 💡 My Approach: Created a Student class Implemented a custom Comparator Used Collections.sort() to sort the list 💻 Java Implementation: import java.util.*; class Student { private int id; private String fname; private double cgpa; public Student(int id, String fname, double cgpa) { this.id = id; this.fname = fname; this.cgpa = cgpa; } public int getId() { return id; } public String getFname() { return fname; } public double getCgpa() { return cgpa; } } // Comparator class CGPAComparator implements Comparator<Student> { @Override public int compare(Student s1, Student s2) { if(s1.getCgpa()==s2.getCgpa() && s1.getFname().equals(s2.getFname())) { if(s1.getId()<s2.getId()) return -1; else if(s1.getId()>s2.getId()) return 1; else return 0; } if (s1.getCgpa() < s2.getCgpa()) return 1; else if (s1.getCgpa() > s2.getCgpa()) return -1; else { int nameCompare = s1.getFname().compareTo(s2.getFname()); if (nameCompare == 0) return s1.getId() - s2.getId(); else return nameCompare; } } } public class Solution { public static void main(String[] args) { Scanner in = new Scanner(System.in); int testCases = Integer.parseInt(in.nextLine()); List<Student> studentList = new ArrayList<>(); while (testCases > 0) { int id = in.nextInt(); String fname = in.next(); double cgpa = in.nextDouble(); studentList.add(new Student(id, fname, cgpa)); testCases--; } Collections.sort(studentList, new CGPAComparator()); for (Student st : studentList) { System.out.println(st.getFname()); } } } 🎯 Key Learning: How to implement multi-level sorting Importance of Comparator in real-world scenarios Clean and readable sorting logic for interviews 💬 If you're preparing for Java interviews, this is a must-practice question! #Java #Programming #Coding #DataStructures #InterviewPreparation #Comparator #JavaDeveloper #LearningJourney
To view or add a comment, sign in
-
🚀 Java Learning – Day 7 📌 Topic: Strings in Java 🔹 What is a String? A String is used to store text (sequence of characters). Example: String name = "John"; 🔹 Why do we use Strings? • To store names, messages, and text data • Widely used in real-world applications 🔹 String Methods • length() → returns length of string • toUpperCase() → converts to uppercase • toLowerCase() → converts to lowercase • charAt() → returns character at index 🔹 Example public class Main { public static void main(String[] args) { String name = "Java"; System.out.println(name.length()); System.out.println(name.toUpperCase()); System.out.println(name.toLowerCase()); System.out.println(name.charAt(1)); } } 🔹 Output 4 JAVA java a I have shared my handwritten notes below 👇 Feel free to correct me or add suggestions 🙌 #Java #Strings #JavaLearning #LearningInPublic #100DaysOfCode #Programming #CodingJourney #BackendDevelopment #TechLearning #CareerGrowth #OpenToWork
To view or add a comment, sign in
-
-
🚀 Java 8 Coding Questions (Part 2 – Based on My Interviews) After sharing Core Java coding questions, here are Java 8 specific coding questions that were frequently asked 👇 🔹 Streams + Object Mapping Convert given string data into List of Employee objects and sort in ascending order of ID String empDetails1 ="1,AAAAA,develop,234566||3,NNNNN,QA,78977"; String empDetails2 ="4,BBBBB,develop,1234||2,KKKKKK,develop,67678"; String empDetails3 ="5,CCCCC,Manager,89888"; 🔹 Sorting with Java 8 Sort employee list by name, if name is same then sort by salary Sort list of students based on name, branch, address Sort employee list by name in descending order Sort list of students by marks, if marks same then sort by name Sort strings by length 🔹 Grouping & Filtering Group employees by department and sort them by salary (ascending) Print employee names whose salary is greater than 40K Return employees whose salary is greater than their manager’s salary 🔹 Frequency Based Questions Count frequency of words in a string Example: "java is a good language..." → java = 3 Count frequency of elements in list Example: ["Pen", "Eraser", "Pen", "Pencil"] 🔹 List / Number Based Find frequency of each element in list Shift all zeros to the end of list Find second highest number in list/array Sort numbers that start with digit 1 Find max and min from given list 🔹 String-Based (Java 8) Find first repeated character in a string Find first non-repeated character in a string 🔹 Data Structure Style Employee structure: id, name, managerId, salary 👉 Return employees whose salary is greater than their manager 💡 Observation: Java 8 questions focus heavily on: Streams API Sorting & Comparator Filtering & Mapping Grouping & Collectors 🔥 Save this for preparation — these are commonly asked in modern Java interviews #Java8 #Streams #JavaDeveloper #CodingInterview #InterviewPreparation
To view or add a comment, sign in
-
🚀 Java Collections Framework – From Basics to Deep Understanding (Visual Guide) If you're learning Java or preparing for interviews, this is one topic you simply cannot skip — the Collections Framework. I created this visual to simplify not just the hierarchy, but also the internal behavior and real use-cases of each collection 👇 🔹 Start from the Root Iterable → Enables iteration Collection → Core interface for all collections 🔹 Core Interfaces Explained ✔ List → Ordered, duplicates allowed ✔ Set → Unique elements, no duplicates ✔ Queue → FIFO processing ✔ Map → Key-Value pairs (separate hierarchy) 🔹 Deep Dive into Implementations 💡 ArrayList Dynamic array Fast read (O(1)) Slow insert/delete (shift happens) 💡 LinkedList Doubly linked list Fast insertion/deletion Slow random access 💡 HashSet Uses hashing No duplicates No order 💡 LinkedHashSet Maintains insertion order Combines HashSet + LinkedList 💡 TreeSet Sorted data (Red-Black Tree) O(log n) operations 🔹 Map Internals (Very Important 🔥) 💡 HashMap Key-Value structure Uses hashing Very fast (O(1) average) 💡 LinkedHashMap Maintains insertion order 💡 TreeMap Sorted keys Based on Red-Black Tree 🔹 Queue Implementations ✔ PriorityQueue → Sorted elements ✔ ArrayDeque → Double-ended queue 🔥 Golden Rule 👉 “We don’t create objects of interfaces, we use their implementations.” List<Integer> list = new ArrayList<>(); 💡 Why this matters? Because in interviews, you’ll be asked: Difference between ArrayList vs LinkedList How HashMap works internally When to use Set vs List vs Map 📌 Pro Tip Always choose collection based on: Performance Ordering requirement Duplicate handling 💬 If this helped you, comment “COLLECTIONS” and I’ll share advanced interview questions on this topic. 📌 Save this for revision 🔁 Share with your friends preparing for Java #Java #JavaDeveloper #CollectionsFramework #DSA #CodingInterview #Programming #LearnJava #TechContent Durgesh Tiwari Anshika Singh Rohit Negi
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