Day 4 – Sorting in Java Collections | Comparable vs Comparator | Custom Object Sorting (Backend Developer Learning Series) Today I deeply revised how sorting works in Java Collections — especially with custom objects, which is extremely important in backend development. 📌 Sorting in Collection Framework In Java, we use the Collections utility class (java.util.Collections) to perform sorting and other helper operations. 🔹 Common Methods: Collections.sort(list) → Ascending order Collections.sort(list, Collections.reverseOrder()) → Descending Collections.reverse(list) Collections.max(list) Collections.min(list) Collections.unmodifiableList(list) Collections.synchronizedList(list) 💡 Collections class provides static helper methods for collection operations. 🔥 Sorting Custom Objects In real backend applications, we don’t sort integers or strings only. We sort objects like: Employee Product Student Orders Transactions These objects contain multiple properties. To sort them, Java provides two approaches: 1️⃣ Comparable (Default Sorting Logic) Defined in java.lang package Contains one abstract method: public int compareTo(Object o); ✔ Used when: You want default sorting logic Only one type of sorting is needed ✔ Implemented inside the class itself Example: public class Employee implements Comparable<Employee> { public int compareTo(Employee e) { return this.id - e.id; // Ascending by id } } Then: Collections.sort(employeeList); 2️⃣ Comparator (Multiple Sorting Logic) Defined in java.util package Contains: public int compare(Object o1, Object o2); ✔ Used when: Multiple sorting logic required Don’t want to modify blueprint class Sorting based on different fields Example: Collections.sort(list, new SortByIdDesc()); Collections.sort(list, new SortByPriceAsc()); Collections.sort(list, new SortByNameAsc()); #Java #BackendDeveloper #Collections #Comparable #Comparator #SpringBoot #LearningInPublic #InterviewPreparation #SoftwareEngineering
Java Collections Sorting: Comparable vs Comparator
More Relevant Posts
-
ArrayList ✈️ In Java, an ArrayList is a member of the Java Collections Framework and resides in the java.util package. While a standard Java array (e.g., int[]) is fixed in length, an ArrayList is a resizable-array implementation of the List interface. How It Works: The "Growing" Mechanism When you add an element to an ArrayList, Java checks if there is enough room in the underlying memory. If the internal array is full, the ArrayList performs the following: It allocates a new, larger array ✅Key Features in Java Type Safety: It uses Generics, allowing you to specify what type of data it holds (e.g., ArrayList<String>). Wrapper Classes: It cannot store primitive types (like int, double, char) directly. Instead, Java uses "Autoboxing" to convert them into objects (like Integer, Double, Character). Nulls and Duplicates: It allows you to store duplicate elements and null values. Unsynchronized: By default, it is not thread-safe. If multiple threads access it simultaneously, you must handle synchronization manually. It copies all existing elements to the new array. It updates its internal reference to this new array. ✅ArrayList vs. LinkedList A common interview question is when to use ArrayList over LinkedList. ArrayList: Best for frequent access and storing data where you mostly add/remove from the end. LinkedList: Best if you are constantly inserting or deleting items from the beginning or middle of the list. Would you like me to explain the specific differences between ArrayList and Vector, or perhaps show you how to sort an ArrayList using Collections.sort(). Huge thanks for the mentorship on Java ArrayList Anand Kumar Buddarapu Saketh Kallepu Uppugundla Sairam #ArrayList #Java #DataStructures #Programming #Coding #SoftwareEngineering #Backend #JavaDeveloper #Algorithms #TechTips #ComputerScience
To view or add a comment, sign in
-
🚀 Java Series – Day 18 📌 Serialization in Java (Why Serializable is a Marker Interface?) 🔹 What is it? Serialization is the process of converting a Java object into a byte stream so it can be stored in a file or transferred over a network. The reverse process is called Deserialization. Java uses the Serializable interface to enable serialization. 🔹 Why do we use it? Serialization is useful when we want to save object state or send objects across systems. For example: In a banking or login system, user session data can be serialized and stored, then later restored when needed. 🔹 Why is Serializable a Marker Interface? A marker interface is an empty interface (no methods) that signals the JVM to perform special behavior. "Serializable" does not contain any methods. It simply tells the JVM: 👉 “This object is allowed to be converted into a byte stream.” If a class does not implement "Serializable", Java will throw a NotSerializableException. 🔹 Example: import java.io.*; class Student implements Serializable { int id; String name; Student(int id, String name) { this.id = id; this.name = name; } } public class Main { public static void main(String[] args) throws Exception { Student s = new Student(1, "Raushan"); // Serialization ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("data.txt")); out.writeObject(s); out.close(); System.out.println("Object Serialized"); } } 💡 Key Takeaway: "Serializable" is a marker interface that enables object serialization without defining any methods. What do you think about this? 👇 #Java #Serialization #JavaDeveloper #Programming #BackendDevelopment
To view or add a comment, sign in
-
-
🚀 Java Series – Day 21 📌 Inner Classes in Java (Static vs Non-Static) 🔹 What is it? An Inner Class is a class defined inside another class. Java provides different types of inner classes: • Member Inner Class (Non-static) • Static Nested Class • Local Inner Class (inside method) • Anonymous Inner Class 🔹 Why do we use it? Inner classes help in logical grouping of classes and improve code readability & encapsulation. For example: In a banking system, a "Bank" class can contain an inner class "Account" to tightly couple related logic. 🔹 Static vs Non-Static Inner Class: • Non-Static Inner Class (Member Inner Class) - Requires outer class object - Can access all members of outer class - Used when inner class depends on outer class • Static Inner Class (Static Nested Class) - Does NOT require outer class object - Can access only static members of outer class - Used for utility/helper classes 🔹 Example: class Outer { int x = 10; static int y = 20; // Non-static inner class class Inner { void display() { System.out.println("x = " + x); // can access all } } // Static inner class static class StaticInner { void display() { System.out.println("y = " + y); // only static access } } } public class Main { public static void main(String[] args) { // Non-static inner class Outer outer = new Outer(); Outer.Inner inner = outer.new Inner(); inner.display(); // Static inner class Outer.StaticInner obj = new Outer.StaticInner(); obj.display(); } } 💡 Key Takeaway: Use non-static inner classes when tightly coupled with outer class, and static inner classes for independent utility behavior. What do you think about this? 👇 #Java #InnerClass #JavaDeveloper #Programming #BackendDevelopment
To view or add a comment, sign in
-
-
DAY 24: CORE JAVA 💻 Understanding Buffer Problem & Wrapper Classes in Java While working with Java input using Scanner, many beginners face a common issue called the Buffer Problem. 🔹 What is the Buffer Problem? When we use "nextInt()", "nextFloat()", etc., the scanner reads only the number but leaves the newline character ("\n") in the input buffer. Example: Scanner scan = new Scanner(System.in); int n = scan.nextInt(); // reads number String name = scan.nextLine(); // reads leftover newline ⚠️ The "nextLine()" does not wait for user input because it consumes the leftover newline from the buffer. ✅ Solution: Use an extra "nextLine()" to clear the buffer. int n = scan.nextInt(); scan.nextLine(); // clears the buffer String name = scan.nextLine(); 📌 This is commonly called a dummy nextLine() to flush the buffer. 🔹 Wrapper Classes in Java Java provides Wrapper Classes to convert primitive data types into objects. Primitive Type| Wrapper Class byte| Byte short| Short int| Integer long| Long float| Float char| Character 💡 Wrapper classes allow: - Converting String to primitive values - Storing primitive data in collections - Using useful utility methods Example: String s = "123"; int num = Integer.parseInt(s); // String → int 🔹 Example Use Case Suppose employee data is entered as a string: 1,Swathi,30000 We can split and convert values using wrapper classes: String[] arr = s.split(","); int empId = Integer.parseInt(arr[0]); String empName = arr[1]; int empSal = Integer.parseInt(arr[2]); 🚀 Key Takeaways ✔ Always clear the buffer when mixing "nextInt()" and "nextLine()" ✔ Wrapper classes help convert String ↔ primitive types ✔ They are essential when working with input processing and collections 📚 Concepts like these strengthen the core Java foundation for developers and interview preparation. TAP Academy #Java #CoreJava #JavaProgramming #WrapperClasses #Programming #SoftwareDevelopment
To view or add a comment, sign in
-
-
🚀 Java Series – Day 19 📌 Multithreading in Java (Thread vs Runnable) 🔹 What is it? Multithreading is a process of executing multiple threads simultaneously to perform tasks efficiently. A thread is a lightweight unit of execution within a program. Java provides two main ways to create threads: • Extending the Thread class • Implementing the Runnable interface 🔹 Why do we use it? Multithreading helps improve performance and responsiveness. For example: In a web application, one thread can handle user requests while another processes background tasks like data saving or logging. 🔹 Thread vs Runnable: • Thread Class - Extend "Thread" - Less flexible (Java doesn’t support multiple inheritance) • Runnable Interface - Implement "Runnable" - More flexible (can extend another class) - Preferred approach in real-world applications 🔹 Example: // Using Thread class MyThread extends Thread { public void run() { System.out.println("Thread using Thread class"); } } // Using Runnable class MyRunnable implements Runnable { public void run() { System.out.println("Thread using Runnable"); } } public class Main { public static void main(String[] args) { MyThread t1 = new MyThread(); t1.start(); Thread t2 = new Thread(new MyRunnable()); t2.start(); } } 💡 Key Takeaway: Use Runnable for better flexibility and scalability in multithreaded applications. What do you think about this? 👇 #Java #Multithreading #JavaDeveloper #Programming #BackendDevelopment
To view or add a comment, sign in
-
-
☕ JSON.simple in Java – Escaping Special Characters When working with JSON strings in Java, certain characters are considered reserved characters and cannot be used directly. These characters must be escaped properly to ensure the JSON format remains valid. java explanations (28) As shown on Page 1, JSON uses escape sequences to represent these special characters inside strings. 🔹 Reserved Characters in JSON The document lists the following characters and their escape sequences: Backspace → \b Form Feed → \f New Line → \n Carriage Return → \r Tab → \t Double Quote → \" Backslash → \\ These escape sequences allow JSON strings to safely include special characters. 🔹 Escaping Special Characters Using JSON.simple The library provides the JSONObject.escape() method to automatically escape reserved characters in a string. Example program shown on Page 2: import org.json.simple.JSONObject; public class JsonDemo { public static void main(String[] args) { JSONObject jsonObject = new JSONObject(); String text = "Text with special character /\"'\b\f\t\r\n."; System.out.println(text); System.out.println("After escaping."); text = jsonObject.escape(text); System.out.println(text); } } This program demonstrates how special characters are converted into their escaped versions. 🔹 Program Output As shown on Page 5, the output displays the original string and the escaped string. Original text: Text with special character /"' . After escaping: Text with special character \/\"'\b\f\t\r\n. This ensures the string becomes valid JSON-compatible text. 💡 Escaping special characters is essential when generating JSON data dynamically in Java applications, APIs, or microservices to prevent parsing errors and maintain data integrity. #Java #JSON #JSONSimple #JavaProgramming #BackendDevelopment #API #SoftwareDevelopment #AshokIT
To view or add a comment, sign in
-
🚀 Mastering Core Java | Day 10 📘 Topic: Exception Handling Today’s session focused on Exception Handling, a critical concept in Java that helps manage runtime errors gracefully and ensures smooth program execution. 🔑 What is an Exception? An unexpected event that disrupts normal program flow Occurs during execution (e.g., invalid input, missing files, divide by zero) If not handled, it can cause program termination 🧠 Why Exception Handling is Important? Prevents application crashes Improves program reliability and stability Separates error-handling logic from core business logic Makes debugging and maintenance easier 🧩 Key Keywords in Exception Handling: try – Contains risky code catch – Handles the exception finally – Executes whether an exception occurs or not throw / throws – Used to explicitly pass exceptions Simple Syntax & Example: try { int result = 10 / 0; } catch (ArithmeticException e) { System.out.println("Cannot divide by zero"); } finally { System.out.println("Execution completed"); } 📌 Types of Exceptions: Compile‑Time (Checked) – Detected at compile time Examples: IOException, SQLException Run‑Time (Unchecked) – Occur during execution Examples: NullPointerException, ArrayIndexOutOfBoundsException, ArithmeticException 💡 Key Takeaway: Exception Handling allows applications to handle errors gracefully, improving user experience and making systems more robust. Grateful to my mentor Vaibhav Barde sir for the clear explanations and real‑world examples, which made this concept easy to understand and apply. 📈 Continuing to strengthen my Core Java and OOP fundamentals step by step. #ExceptionHandling #CoreJava #JavaLearning #Day10 #OOPConcepts #SoftwareDevelopment #LearningJourney #ProfessionalGrowth
To view or add a comment, sign in
-
-
🚀 Java 8 – One of the Most Important Releases in Java History Java 8 introduced powerful features that completely changed how developers write Java code. It brought functional programming concepts, cleaner syntax, and more efficient data processing. Here are some of the most important features every Java developer should know 👇 🔹 1. Lambda Expressions Lambda expressions allow writing concise and readable code for functional interfaces. Example: List<String> names = Arrays.asList("Ali", "Sara", "John"); names.forEach(name -> System.out.println(name)); Instead of writing a full anonymous class, we can use a short lambda expression. 🔹 2. Functional Interfaces An interface with only one abstract method is called a functional interface. Example: @FunctionalInterface interface Calculator { int add(int a, int b); } Lambda expressions work with functional interfaces. 🔹 3. Stream API Stream API allows developers to process collections in a functional style. Example: List<Integer> numbers = Arrays.asList(1,2,3,4,5,6); numbers.stream() .filter(n -> n % 2 == 0) .forEach(System.out::println); Benefits: ✔ Less boilerplate code ✔ Better readability ✔ Easy parallel processing 🔹 4. Method References Method references make lambda expressions even shorter and cleaner. Example: names.forEach(System.out::println); Instead of: names.forEach(name -> System.out.println(name)); 🔹 5. Optional Class "Optional" helps avoid NullPointerException. Example: Optional<String> name = Optional.ofNullable(null); System.out.println(name.orElse("Default Name")); 💡 Why Java 8 is still widely used ✔ Introduced functional programming in Java ✔ Improved code readability ✔ Simplified collection processing ✔ Reduced boilerplate code Java 8 fundamentally changed the way modern Java applications are written. #Java #Java8 #Programming #SoftwareDevelopment #JavaDeveloper #Coding
To view or add a comment, sign in
-
-
Core Java (Deep Concepts): 1️⃣ What happens internally in HashMap when two keys generate the same hash? Collision occurs. HashMap stores entries in buckets indexed by hash(key). Before Java 8: linked list. Java 8+: red-black tree if list grows beyond 8. equals() is checked for key match. 2️⃣ How does ConcurrentHashMap achieve thread safety? Fine-grained locking or CAS for writes. Reads mostly lock-free. Allows concurrent read/write without locking the entire map. 3️⃣ Difference between Synchronized Collections and Concurrent Collections: Synchronized: coarse-grained, single-thread access, e.g., Collections.synchronizedList. Concurrent: fine-grained, multiple threads can access, e.g., ConcurrentHashMap. 4️⃣ Volatile vs Synchronization: Volatile: ensures visibility only, no mutual exclusion. Synchronization: ensures visibility + mutual exclusion. 5️⃣ Explain Java Memory Model (JMM): Defines thread interactions via memory. Key concepts: main memory vs CPU cache, happens-before relationship, visibility with volatile, atomicity with synchronized. 6️⃣ Difference between Future and CompletableFuture: Future: waits for the result, limited. CompletableFuture: async, chaining, handles exceptions, supports multiple futures. 7️⃣ Parallel Streams: Executes operations in parallel via ForkJoinPool. Avoid when shared mutable state exists, small datasets, or ordering matters. 8️⃣ ClassLoader in Java: Loads class bytecode into JVM. Types: Bootstrap, Extension, System/Application, Custom. 9️⃣ Sealed Classes Allows developers to restrict which classes can extend or implement a class or interface, improving domain modeling and security. 🔟 What is a record in Java? A record is a special type of class used to model immutable data objects with very little boilerplate code. It automatically generates: constructor getters equals() hashCode() toString()
To view or add a comment, sign in
-
🚀 Java Keywords Cheat Sheet – Must Know for Every Java Developer If you're preparing for Java interviews, coding tests, or strengthening your programming fundamentals, understanding Java keywords is essential. These keywords define the structure, logic, and behavior of Java programs. Here is a quick breakdown of the most important categories: 🔹 1. Data Types Java provides primitive data types such as "byte", "short", "int", "long", "float", "double", "char", and "boolean" to store different types of values. Example: "int age = 25;" 🔹 2. Control Flow Statements These keywords control the execution flow of a program. Examples include "if", "else", "for", "while", "switch", "break", and "continue". Example: Using "if-else" to check conditions. 🔹 3. OOP Concepts Java is an object-oriented programming language. Keywords like "class", "interface", "extends", "implements", "this", "super", and "abstract" help create reusable and structured code. 🔹 4. Access Modifiers These control the visibility of variables and methods. "public" – accessible everywhere "private" – accessible only inside the class "protected" – accessible within package and subclasses. 🔹 5. Exception Handling Java handles runtime errors using "try", "catch", "finally", "throw", and "throws" to make applications more reliable. 🔹 6. Threads Keywords like "synchronized" and "volatile" are used in multithreading to manage shared resources safely. 🔹 7. Modules (Java 9+) Keywords such as "module", "requires", "exports", "opens", and "provides" help organize large applications into modular structures. 🔹 8. Other Important Keywords "import", "return", "void", "instanceof", "record", and "assert" are used for various programming operations. ⚠️ Note: "true", "false", and "null" are reserved literals in Java and cannot be used as identifiers. 💡 Tip: Mastering these keywords helps in writing clean code, understanding frameworks, and clearing technical interviews. #Java #Programming #JavaDeveloper #Coding #SoftwareDevelopment #OOP #TechLearning
To view or add a comment, sign in
-
More from this author
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