The Programmer's Guide
  • About
  • Algorithm
    • Big O Notation
      • Tree
      • Problems
    • Basic Notes
    • Data Structure Implementation
      • Custom LinkedList
      • Custom Stack
      • Custom Queue
      • Custom Tree
        • Binary Tree Implementation
        • Binary Search Tree Implementation
        • Min Heap Implementation
        • Max Heap Implementation
        • Trie Implementation
      • Custom Graph
        • Adjacency List
        • Adjacency Matrix
        • Edge List
        • Bidirectional Search
    • Mathematical Algorithms
      • Problems - Set 1
      • Problems - Set 2
    • Bit Manipulation
      • Representation
      • Truth Tables
      • Number System
        • Java Program
      • Problems - Set 1
    • Searching
    • Sorting
    • Array Algorithms
    • String Algorithms
    • Tree
      • Tree Traversal Techniques
      • Tree Implementation
      • Applications of Trees
      • Problems - Set 1
    • Graph
      • Graph Traversal Techniques
      • Shortest Path Algorithms
      • Minimum Spanning Tree (MST) Algorithms
    • Dynamic Programming
      • Problems - Set 1
    • Recursion
    • Parallel Programming
    • Miscellaneous
      • Problems - Set 1
  • API
    • API Basics
      • What is an API?
      • Types of API
        • Comparison - TBU
      • Synchronous vs Asynchronous API
    • API Architecture
      • Synchronous & Asynchronous Communication
    • API Specification
  • Cloud Computing
    • Cloud Fundamentals
      • Cloud Terminology
      • Core Terminology
      • Cloud Models
      • Cloud Service Models
      • Benefits, Challenges and Risk of Cloud Computing
      • Cloud Ecosystem
  • Database
    • DBMS
      • Types of DBMS
        • Relational DBMS (RDBMS)
        • NoSQL DBMS
        • Object-Oriented DBMS (OODBMS)
        • Columnar DBMS
        • In-Memory DBMS
        • Distributed DBMS
        • Cloud-Based DBMS
        • Hierarchical DBMS
      • DBMS Architecture
      • DBMS Structure
    • SQL Databases
      • Terminology
      • RDBMS Concepts
        • Entity Relationship Diagram (ERD)
          • ERD Examples
        • Normalization
        • Denormalization
        • ACID & BASE Properties
          • ACID Properties
          • BASE Properties
        • Locking and Unlocking
      • SQL Fundamentals
        • SQL Commands
          • DDL (Data Definition Language)
          • DML (Data Manipulation Language)
          • DCL (Data Control Language)
          • TCL (Transaction Control Language)
          • DQL (Data Query Language)
        • SQL Operators
          • INTERSECT
          • EXCEPT
          • MINUS
          • IN and NOT IN
          • EXISTS and NOT EXISTS
        • SQL Clauses
          • Joins
          • OVER
          • WITH
          • CONNECT BY
          • MODEL
          • FETCH FIRST
          • KEEP
          • OFFSET with FETCH
        • SQL Functions
          • Oracle Specific
        • SQL Data Types
          • Numeric Types
          • Character Types
          • Date & Time Types
          • Large Object Types
        • Others
          • Indexing
      • Vendor Specific Concepts
        • Oracle Specific
          • Data Types
          • Character Set
          • Rownum, Rowid, Urowid
          • Order of Execution of the query
          • Keys
          • Tablespace
          • Partition
      • Best Practice
      • Resources & References
        • O’Reilly SQL Cookbook (2nd Edition)
          • 1. Retrieving Records
          • 2. Sorting Query Results
          • 3. Working with Multiple Tables
          • 4. Inserting, Updating, and Deleting
          • 5. Metadata Queries
          • 6. Working with Strings
          • 7. Working with Numbers
          • 8. Date Arithmetic
          • 9. Date Manipulation
          • 10. Working with Ranges
          • 11. Advanced Searching
          • 12. Reporting and Reshaping
          • 13. Hierarchical Queries
          • 14. Odds 'n' Ends
    • SQL vs NoSQL
    • Best Practices
  • Git
    • Commands
      • Setup and Configuration Commands
      • Getting and Creating Projects
      • Tracking Changes
      • Branching and Merging
      • Sharing and Updating Projects
      • Inspection and Comparison
      • Debugging
      • Patching
      • Stashing and Cleaning
      • Advanced Manipulations
    • Workflows
      • Branching Strategies
        • Git Flow
        • Trunk-Based Development
        • GitHub Flow
        • Comparison
      • Merge Strategies
        • Merge
        • Rebase
        • Squash
        • Fast-forward vs No-fast-forward
        • MR vs PR
      • Conflict Resolution
        • Handling Merge Conflicts
        • Merge Conflicts
        • Rebase Conflicts
        • Divergent Branches After git pull
        • Force Push
      • Patch & Recovery
        • Cherry-pick strategies
        • Revert vs Reset
        • Recover from a bad rebase
      • Rebasing Practices
        • Merge vs Rebase
        • Rebase develop branch on main branch
      • Repository Management
        • Working Directory
        • Mirror a repository
        • Convert a local folder to a Git repo
        • Backup and restore a Git repository
  • Java
    • Java Installation
    • Java Distributions
    • Java Platform Editions
      • Java SE
      • Java EE
      • Jakarta EE
      • Java ME
      • JavaFX
    • Java Overview
      • OOP Principles
        • Encapsulation
        • Inheritance
        • Polymorphism
        • Abstraction
          • Abstract Class & Method
          • Interface
            • Functional Interfaces
            • Marker Interfaces
          • Abstract Class vs Interface
      • OOP Basics
        • What is a Class?
          • Types of Classes
        • What is an Object?
          • Equals and HashCode
            • FAQ
          • Shallow Copy and Deep Copy
          • Ways to Create Object
          • Serialization & Deserialization
        • Methods & Fields
          • Method Overriding & Overloading
          • Method Signature & Header
          • Variables
        • Constructors
        • Access Modifiers
      • Parallelism & Concurrency
        • Ways to Identify Thread Concurrency or Parallelism
        • Thread Basics
          • Thread vs Process
          • Creating Threads
          • Thread Context Switching
          • Thread Lifecycle & States
          • Runnable & Callable
          • Types of Threads
          • Thread Priority
        • Thread Management & Synchronisation
          • Thread Resource Sharing
          • Thread Synchronization
            • Why is Synchronization Needed?
            • Synchronized Blocks & Methods
          • Thread Lock
            • Types of Locks
            • Intrinsic Lock (Monitor Lock)
            • Reentrant Lock
          • Semaphore
          • Thread Starvation
          • Thread Contention
          • Thread Deadlock
          • Best Practices for Avoiding Thread Issues
      • Keywords
        • this
        • super
        • Access Modifiers
      • Data Types
        • Default Values
        • Primitive Types
          • byte
          • short
          • int
          • long
          • float
          • double
          • char
          • boolean
        • Non-Primitive (Reference) Types
          • String
            • StringBuilder
            • StringBuffer
              • Problems
            • Multiline String
            • Comparison - String, StringBuilder & StringBuffer
          • Array
          • Collections
            • List
              • Array vs List
              • ArrayList
              • Vector
                • Stack
                  • Problems
              • LinkedList
            • Queue
              • PriorityQueue
              • Deque (Double-Ended Queue)
                • ArrayDeque
                • ConcurrentLinkedDeque - TBU
                • LinkedBlockingDeque - TBU
            • Map
              • HashMap
              • Hashtable
              • LinkedHashMap
              • ConcurrentHashMap
              • TreeMap
              • EnumMap
              • WeakHashMap
            • Set
              • HashSet
              • LinkedHashSet
              • TreeSet
              • EnumSet
              • ConcurrentSkipListSet
              • CopyOnWriteArraySet
        • Specialized Classes
          • BigInteger
          • BigDecimal
            • Examples
          • BitSet
          • Date and Time
            • Examples
          • Optional
          • Math
          • UUID
          • Scanner
          • Formatter
            • Examples
          • Properties
          • Regex (Pattern and Matcher)
            • Examples
          • Atomic Classes
          • Random
          • Format
            • NumberFormat
            • DateFormat
            • DecimalFormat
        • Others
          • Object
          • Enum
            • Pre-Defined Enum
            • Custom Enum
            • EnumSet and EnumMap
          • Record
          • Optional
          • System
          • Runtime
          • ProcessBuilder
          • Class
          • Void
          • Throwable
            • Error
            • Exception
              • Custom Exception Handling
              • Best Practice
            • Error vs Exception
            • StackTraceElement
    • Java Features by Version
      • How New Java Features are Released ?
      • Java Versions
        • Java 8
        • Java 9
        • Scoped Values
        • Unnamed Variables & Patterns
      • FAQ
    • Concepts
      • Set 1
        • Streams
          • flatmap
          • Collectors Utility Class
          • Problems
        • Functional Interfaces
          • Standard Built-In Interfaces
          • Custom Interfaces
        • Annotation
          • Custom Annotation
          • Meta Annotation
        • Generics
          • Covariance and Invariance
        • Asynchronous Computation
          • Future
          • CompletableFuture
          • Future v/s CompletableFuture
          • ExecutorService
            • Thread Pool
            • Types of Work Queues
            • Rejection Policies
            • ExecutorService Implementations
            • ExecutorService Usage
          • Locks, Atomic Variables, CountDownLatch, CyclicBarrier - TBU
          • Parallel Streams, Fork/Join Framework,Stream API with Parallelism - TBU
      • Set 2
        • Standards
          • ISO Standards
          • JSR
            • JSR 303, 349, 380 (Bean Validation)
        • Operator Precedence
      • Set 3
        • Date Time Formatter
        • Validation
      • Set 4
        • Input from User
        • Comparison & Ordering
          • Object Equality Check
          • Comparable and Comparator
            • Comparator Interface
          • Sorting of Objects
          • Insertion Ordering
    • Packages
      • Core Packages
        • java.lang
          • java.lang.System
          • java.lang.Thread
      • Jakarta Packages
        • jakarta.validation
        • javax.validation
      • Third-party Packages
    • Code Troubleshoot
      • Thread Dump
      • Heap Dump
    • Code Quality & Analysis
      • ArchUnit
      • Terminologies
        • Cyclic dependencies
    • Code Style
      • Naming Convention
      • Package Structure
      • Formatting
      • Comments and Documentation
      • Imports
      • Exception Handling
      • Class Structure
      • Method Guidelines
      • Page 1
      • Code Smells to Avoid
      • Lambdas and Streams Style
      • Tools
    • Tools
      • IntelliJ IDEA
        • Shortcuts for MAC
      • Apache JMeter
        • Examples
      • Thread Dump Capture
        • jstack
        • VisualVM - TBU
        • jcmd - TBU
        • JConsole - TBU
        • YourKit Java Profiler - TBU
        • Eclipse MAT - TBU
        • IntelliJ IDEA Profiler - TBU
        • AppDynamics - TBU
        • Dynatrace - TBU
        • Thread Dump Analyzers - TBU
      • Heap Dump Capture
        • jmap
        • VisualVM - TBU
        • jcmd - TBU
        • Eclipse MAT (Memory Analyzer Tool) - TBU
        • IntelliJ IDEA Profiler - TBU
        • YourKit Java Profiler - TBU
        • AppDynamics - TBU
        • Dynatrace - TBU
        • Kill -3 Command - TBU
        • jhat (Java Heap Analysis Tool) - TBU
        • JVM Options - TBU
      • Wireshark
        • Search Filters
    • Best Practices
      • Artifact and BOM Versioning
  • Maven
    • Installation
    • Local Repository & Configuration
    • Command-line Options
    • Build & Lifecycle
    • Dependency Management
      • Dependency
        • Transitive Dependency
        • Optional Dependency
      • Dependency Scope
        • Maven Lifecycle and Dependency Scope
      • Dependency Exclusions & Overrides
      • Bill of Materials (BOM)
      • Dependency Conflict Resolution
      • Dependency Tree & Analysis
      • Dependency Versioning Strategies
    • Plugins
      • Build Lifecycle Management
      • Dependency Management
      • Code Quality and Analysis
      • Documentation Generation
      • Code Generation
      • Packaging and Deployment
      • Reporting
      • Integration and Testing
      • Customization and Enhancement
        • build-helper-maven-plugin
        • properties-maven-plugin
        • ant-run plugin
        • exec-maven-plugin
        • gmavenplus-plugin
      • Performance Optimization
    • FAQs
      • Fixing Maven SSL Issues: Unable to Find Valid Certification Path
  • Spring
    • Spring Basics
      • What is Spring?
      • Why Use Spring
      • Spring Ecosystem
      • Versioning
      • Setting Up a Spring Project
    • Core Concepts
      • Spring Core
        • Dependency Injection (DI)
        • Stereotype Annotation
      • Spring Beans
        • Bean Lifecycle
        • Bean Scope
          • Singleton Bean
        • Lazy & Eager Initialization
          • Use Case of Lazy Initialization
        • BeanFactory
        • ApplicationContext
      • Spring Annotations
        • Spring Boot Specific
        • Controller Layer (Web & REST Controllers)
    • Spring Features
      • Auto Configuration
        • Spring Boot 2: spring.factories
        • Spring Boot 3: spring.factories
      • Spring Caching
        • In-Memory Caching
      • Spring AOP
        • Before Advice
        • After Returning Advice
        • After Throwing Advice
        • After (finally) Advice
        • Around Advice
      • Spring File Handling
      • Reactive Programming
        • Reactive System
        • Reactive Stream Specification
        • Project Reactor
          • Mono & Flux
      • Asynchronous Computation
        • @Async annotation
      • Spring Security
        • Authentication
          • Core Components
            • Security Filter Chain
              • HttpSecurity
              • Example
            • AuthenticationManager
            • AuthenticationProvider
            • UserDetailsService
              • UserDetails
              • PasswordEncoder
            • SecurityContext
            • SecurityContextHolder
            • GrantedAuthority
            • Security Configuration (Spring Security DSL)
          • Authentication Models
            • One-Way Authentication
            • Mutual Authentication
          • Authentication Mechanism
            • Basic Authentication
            • Form-Based Authentication
            • Token-Based Authentication (JWT)
            • OAuth2 Authentication
            • Multi-Factor Authentication (MFA)
            • SAML Authentication
            • X.509 Certificate Authentication
            • API Key Authentication
            • Remember-Me Authentication
            • Custom Authentication
          • Logout Handling
        • Authorization
        • Security Filters and Interceptors
        • CSRF
          • Real-World CSRF Attacks & Prevention
        • CORS
        • Session Management and Security
        • Best Practices
      • Spring Persistence
        • JDBC
          • JDBC Components
          • JDBC Template
          • Transaction Management
          • Best Practices in JDBC Usage
          • Datasource
            • Connection Pooling
              • HikariCP
            • Caching
        • JPA (Java Persistence API)
          • JPA Fundamentals
          • ORM Mapping Annotations
            • 1. Entity and Table Mappings
            • 2. Field/Column Mappings
            • 3. Relationship Mappings
            • 4. Inheritance Mappings
            • 5. Additional Configuration Annotations
          • Querying Data
            • JPQL
            • Criteria API
            • JPA Specification
              • Example - Employee Portal
            • Native SQL Queries
            • Named Queries
            • Query Return Types
            • Pagination & Sorting
              • Example - Employee Portal
            • Projection
          • Fetch Strategies in JPA
        • JPA Implementation
          • Hibernate
            • Properties
            • Example
        • Spring Data JPA
          • Repository Abstractions
          • Entity-to-Table Mapping
          • Derived Query Methods
        • Cross-Cutting Concerns
          • Transactions
          • Caching
          • Concurrency
        • Examples
          • Employee Portal
            • API
    • Distributed Systems & Communication
      • Distributed Scheduling
      • Inter-Service Communication
        • 1. RestTemplate
        • 2. WebClient
        • 3. OpenFeign
        • Retry Mechanism
          • @Retryable annotation
            • Example
    • Security & Data Protection
      • Encoding | Decoding
        • Types
          • Base Encoding
            • Base16 - TBD
              • Encoding and Decoding in Java - TBD
            • Base32
              • Encoding and Decoding in Java
            • Base64 -TBD
              • Encoding and Decoding in Java - TBD
          • Text Encoding - TBD
            • Extended ASCII
              • Encoding and Decoding in Java - TBD
                • ISO-8859-1
                • Windows-1252 - TBD
                • IBM Code Pages - TBD
            • ASCII
              • Encoding and Decoding in Java
        • Java Guidelines
          • Text Encoding Decoding Examples
          • Base Encoding Decoding Examples
          • Best Practices and Concepts
          • Libraries
      • Cryptography
        • Terminology
        • Java Cryptography Architecture (JCA)
        • Key Management
          • Key Generation
            • Tools and Libraries
              • OpenSSL
              • Java Keytool
                • Concept
                • Use Cases
            • Key & Certificate File Formats
          • Key Distribution
          • Key Storage
          • Key Rotation
          • Key Revocation
        • Encryption & Decryption
          • Symmetric Encryption
            • Algorithm
            • Modes of Operation
            • Examples
          • Asymmetric Encryption
            • Algorithm
            • Mode of Operation
            • Examples
    • Utilities & Libraries
      • Apache Libraries
        • Apache Camel
          • Camel Architecture
            • Camel Context
            • Camel Endpoints
            • Camel Components
            • Camel Exchange & MEP
          • Spring Dependency
          • Different Components
            • Camel SFTP
        • Apache Commons Lang
      • MapStruct Mapper
      • Utilities by Spring framework
        • FileCopyUtils
    • General Concepts
      • Spring Boot Artifact Packaging
      • Classpath and Resource Loading
      • Configuration - Mapping Properties to Java Class
      • Validations in Spring Framework
        • Jakarta Validation
          • Jakarta Bean Validation Annotations
    • Practical Guidelines
      • Spring Configuration
      • Spring Code Design
  • Software Testing
    • Software Testing Methodologies
      • Functional Testing
      • Non Functional Testing
    • Software Testing Life Cycle (STLC)
    • Integration Test
      • Dynamic Property Registration
    • Java Test Framework
      • JUnit
        • JUnit 4
          • Examples
        • JUnit 5
          • Examples
        • JUnit 4 vs JUnit 5
  • System Design
    • Foundations
      • Programming Paradigms
      • Object-Oriented Design
        • SOLID Principles
        • GRASP Principles
        • Composition
        • Aggregation
        • Association
      • Design Pattern
        • Creational Pattern
        • Structural Pattern
        • Behavioral Pattern
        • Examples
          • Data Collector
          • Payment Processor
        • Design Enhancements
          • Fluent API Design
            • Examples
    • Architectural Building Blocks
      • CAP Theorem
      • Load Balancer
        • Load Balancer Architecture
        • Load Balancing in Java Microservices
          • Client-Side Load Balancing Example
          • Server-Side Load Balancing Example
        • Load Balancer Monitoring Tool
      • Scaling
        • Vertical Scaling (Scaling Up)
        • Horizontal Scaling (Scaling Out)
        • Auto-Scaling
        • Database Scaling via Sharding
      • Caching
        • Pod-Level vs Distributed Caching
      • Networking Metrics
        • Types of Delay
        • Scenario
      • System Characteristics
      • Workload Types
      • Resilience & Failure Handling
    • Performance
      • Why Is My API Sometimes Slow ?
    • Security
      • Security by Design
      • Zero Trust Security Model
      • Zero Trust Architecture
      • Principles
        • CIA
        • Least Privilege Principle
        • Defense in Depth
      • Security Threats & Mitigations
        • OWASP
          • Top 10 Security Threats
          • Application Security Verification Standard
          • Software Assurance Maturity Model
          • Dependency Check
          • CSRFGuard
          • Cheat Sheets
          • Security Testing Guide
          • Threat Dragon
        • Threat Modeling
      • Compliance & Regulation
        • PCI DSS
    • Deployment Patterns
    • Diagrams
      • UML Diagrams
        • PlantUML
          • Class Diagram
          • Object Diagram
          • Sequence Diagram
          • Use Case Diagram
          • Activity Diagram
          • State Diagram
          • Architecture Diagram
          • Component Diagram
          • Timing Diagram
          • ER Diagram (Entity-Relationship)
          • Network Diagram
    • Common Terminologies
    • Problems
      • Reference Materials
      • Cache Design
  • Interview Guide
    • Non-Technical
      • Behavioural or Introductory Guide
      • Project Specific
    • Technical
      • Java Interview Companion
        • Java Key Concepts
          • Set 1
          • Set 2
        • Java Code Snippets
        • Java Practice Programs
          • Set 3 - Strings
          • Set 4 - Search
          • Set 5 - Streams and Collection
      • SQL Interview Companion
        • SQL Practice Problems
          • Set 1
      • Spring Interview Companion
        • Spring Key Concepts
          • Set 1 - General
          • Set 2 - Core Spring
        • Spring Code Snippets
          • JPA
      • Application Server
      • Maven
      • Containerized Application
      • Microservices
    • General
      • Applicant Tracking System (ATS)
      • Flowchart - How to Solve Coding Problem?
Powered by GitBook
On this page
  • Arrays
  • Ascending Order
  • Descending Order
  • List
  • Wrapper Primitive
  • Custom Object - Using Comparator
  • Custom Object - Using Comparable interface
  • Custom Object - Using Lambda expression in Method
  • Sets
  • Wrapper Primitive
  • Custom Objects
  • Maps
  • Wrapper Primitives
  • Custom Object
  • Nested List
  • Wrapper Primitives
  • Custom Object
  • Nested Map
  • Wrapper Primitives
  • Custom Object
  • Nested Set
  • Wrapper Primitives
  • Custom Object
  • Nested List of Set
  • Wrapper Primitives
  • Custom Objects
  • Nested List of Map
  • Wrapper Primitives
  • Custom Object

Was this helpful?

  1. Java
  2. Concepts
  3. Set 4
  4. Comparison & Ordering

Sorting of Objects

Arrays

Ascending Order

// Integer array
int[] intArray = {5, 2, 9, 1, 5, 6};
Arrays.sort(intArray);
System.out.println(Arrays.toString(intArray));

// Character array
char[] charArray = {'b', 'a', 'd', 'c'};
Arrays.sort(charArray);
System.out.println(Arrays.toString(charArray));

// Long array
long[] longArray = {5L, 2L, 9L, 1L, 5L, 6L};
Arrays.sort(longArray);
System.out.println(Arrays.toString(longArray));

// String array
String[] stringArray = {"banana", "apple", "cherry"};
Arrays.sort(stringArray);
System.out.println(Arrays.toString(stringArray));

Descending Order

// Integer array
Integer[] intArray = {5, 2, 9, 1, 5, 6};
Arrays.sort(intArray, Collections.reverseOrder());
System.out.println(Arrays.toString(intArray));

// Character array
Character[] charArray = {'b', 'a', 'd', 'c'};
Arrays.sort(charArray, Collections.reverseOrder());
System.out.println(Arrays.toString(charArray));

// Long array
Long[] longArray = {5L, 2L, 9L, 1L, 5L, 6L};
Arrays.sort(longArray, Collections.reverseOrder());
System.out.println(Arrays.toString(longArray));

// String array
String[] stringArray = {"banana", "apple", "cherry"};
Arrays.sort(stringArray, Collections.reverseOrder());
System.out.println(Arrays.toString(stringArray));

List

Wrapper Primitive

Ascending Order

// Integer list
List<Integer> intList = new ArrayList<>(List.of(5, 2, 9, 1, 5, 6));
Collections.sort(intList);
System.out.println(intList);

// Character list
List<Character> charList = new ArrayList<>(List.of('b', 'a', 'd', 'c'));
Collections.sort(charList);
System.out.println(charList);

// Long list
List<Long> longList = new ArrayList<>(List.of(5L, 2L, 9L, 1L, 5L, 6L));
Collections.sort(longList);
System.out.println(longList);

// String list
List<String> stringList = new ArrayList<>(List.of("banana", "apple", "cherry"));
Collections.sort(stringList);
System.out.println(stringList);

Descending Order

// Integer list
List<Integer> intList = new ArrayList<>(List.of(5, 2, 9, 1, 5, 6));
Collections.sort(intList, Collections.reverseOrder());
// Or intList.sort(Collections.reverseOrder());
System.out.println(intList);

// Character list
List<Character> charList = new ArrayList<>(List.of('b', 'a', 'd', 'c'));
Collections.sort(charList, Collections.reverseOrder());
System.out.println(charList);

// Long list
List<Long> longList = new ArrayList<>(List.of(5L, 2L, 9L, 1L, 5L, 6L));
Collections.sort(longList, Collections.reverseOrder());
System.out.println(longList);

// String list
List<String> stringList = new ArrayList<>(List.of("banana", "apple", "cherry"));
Collections.sort(stringList, Collections.reverseOrder());
System.out.println(stringList);

We can replace Collections.sort(...) with givenList.sort(...). Note that a comparator function is mandatory to pass in sort method here.

For example

intList.sort(Collections.reverseOrder());

Custom Object - Using Comparator

Consider a Person class below as a custom object

public class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }
}

Ascending Order

List<Person> people = new ArrayList<>();
people.add(new Person("Alice", 30));
people.add(new Person("Bob", 25));
people.add(new Person("Charlie", 35));

// Sorting by age in ascending order
Collections.sort(people, Comparator.comparingInt(Person::getAge));
people.forEach(p -> System.out.println(p.getName() + " - " + p.getAge()));

Descending Order

List<Person> people = new ArrayList<>();
people.add(new Person("Alice", 30));
people.add(new Person("Bob", 25));
people.add(new Person("Charlie", 35));

// Sorting by age in descending order
people.sort(Comparator.comparingInt(Person::getAge).reversed());
people.forEach(p -> System.out.println(p.getName() + " - " + p.getAge()));

Custom Object - Using Comparable interface

Create a Java class Pair that represents a pair of integers and provides functionality to sort a collection of its objects based on a custom-defined order.

Requirements:

  1. Attributes:

    • The Pair class should have two integer attributes: first and second.

  2. Constructor:

    • Implement a parameterized constructor that accepts two integers a and b.

    • Initialize the first attribute with a and the second attribute with b.

  3. Custom Sorting Logic:

    • The class should implement the Comparable interface.

    • Define the sorting order using the compareTo method as follows:

      • Sort by the second attribute in descending order.

      • If the second attributes are equal, sort by the first attribute in descending order.

  4. Example: Given an array or list of Pair objects, the custom sorting should work as follows:

    Input:

    Pairs: (3, 4), (1, 4), (5, 2), (2, 2), (3, 3)

    Sorted Output:

    Pairs: (3, 4), (1, 4), (3, 3), (5, 2), (2, 2)
class Pair implements Comparable<Pair> {
    private int first;
    private int second;

    // Parameterized constructor
    public Pair(int a, int b) {
        this.first = a;
        this.second = b;
    }

    // Getters for first and second
    public int getFirst() {
        return first;
    }

    public int getSecond() {
        return second;
    }

    // Override compareTo to define the custom sorting logic
    @Override
    public int compareTo(Pair other) {
        // First compare by second in descending order
        if (this.second != other.second) {
            return Integer.compare(other.second, this.second);
        }
        // If second is the same, compare by first in descending order
        return Integer.compare(other.first, this.first);
    }

    @Override
    public String toString() {
        return "(" + first + ", " + second + ")";
    }

    // Main method
    public static void main(String[] args) {
        // Create a list of Pair objects
        List<Pair> pairs = new ArrayList<>();
        pairs.add(new Pair(3, 4));
        pairs.add(new Pair(1, 4));
        pairs.add(new Pair(5, 2));
        pairs.add(new Pair(2, 2));
        pairs.add(new Pair(3, 3));

        // Sort the pairs using the Comparable interface
        Collections.sort(pairs);

        // Print the sorted list
        for (Pair pair : pairs) {
            System.out.println(pair);
        }
    }
}

Custom Object - Using Lambda expression in Method

    // Method to provide the custom comparator
    public static Comparator<Pair> getCustomComparator() {
        return (p1, p2) -> {
            // Compare by second in descending order
            if (p1.getSecond() != p2.getSecond()) {
                return Integer.compare(p2.getSecond(), p1.getSecond());
            }
            // If second is the same, compare by first in descending order
            return Integer.compare(p2.getFirst(), p1.getFirst());
        };
    }
    
    // We can use like below in the above example
    pairs.sort(Pair.getCustomComparator());

Sets

Wrapper Primitive

We usually use a TreeSet to maintain order.

Ascending Order

// Integer set
Set<Integer> intSet = new TreeSet<>(Set.of(5, 2, 9, 1, 7, 6));
System.out.println(intSet);

// Character set
Set<Character> charSet = new TreeSet<>(Set.of('b', 'a', 'd', 'c'));
System.out.println(charSet);

// Long set
Set<Long> longSet = new TreeSet<>(Set.of(5L, 2L, 9L, 1L, 7L, 6L));
System.out.println(longSet);

// String set
Set<String> stringSet = new TreeSet<>(Set.of("banana", "apple", "cherry"));
System.out.println(stringSet);

Descending Order

// Integer set
Set<Integer> intSet = new TreeSet<>(Collections.reverseOrder());
intSet.addAll(Set.of(5, 2, 9, 1, 7, 6));
System.out.println(intSet);

// Character set
Set<Character> charSet = new TreeSet<>(Collections.reverseOrder());
charSet.addAll(Set.of('b', 'a', 'd', 'c'));
System.out.println(charSet);

// Long set
Set<Long> longSet = new TreeSet<>(Collections.reverseOrder());
longSet.addAll(Set.of(5L, 2L, 9L, 1L, 7L, 6L));
System.out.println(longSet);

// String set
Set<String> stringSet = new TreeSet<>(Collections.reverseOrder());
stringSet.addAll(Set.of("banana", "apple", "cherry"));
System.out.println(stringSet);

Custom Objects

Ascending Order

Set<Person> people = new TreeSet<>(Comparator.comparingInt(Person::getAge));
people.add(new Person("Alice", 30));
people.add(new Person("Bob", 25));
people.add(new Person("Charlie", 35));

people.forEach(p -> System.out.println(p.getName() + " - " + p.getAge()));
Set<Person> personSet = new HashSet<>();
personSet.add(new Person("Alice", 30));
personSet.add(new Person("Bob", 25));
personSet.add(new Person("Charlie", 35));

List<Person> personList = new ArrayList<>(personSet);
personList.sort(Comparator.comparingInt(Person::getAge));

personList.forEach(p -> System.out.println(p.getName() + " - " + p.getAge()));

Descending Order

Set<Person> personSet = new HashSet<>();
personSet.add(new Person("Alice", 30));
personSet.add(new Person("Bob", 25));
personSet.add(new Person("Charlie", 35));

List<Person> personList = new ArrayList<>(personSet);
personList.sort(Comparator.comparingInt(Person::getAge).reversed());

personList.forEach(p -> System.out.println(p.getName() + " - " + p.getAge()));
Set<Person> people = new TreeSet<>(Comparator.comparingInt(Person::getAge).reversed());
people.add(new Person("Alice", 30));
people.add(new Person("Bob", 25));
people.add(new Person("Charlie", 35));

people.forEach(p -> System.out.println(p.getName() + " - " + p.getAge()));

Maps

Maps in Java do not have a natural order, so to sort them we often sort their keys or values and then create a new LinkedHashMap to maintain the order.

Wrapper Primitives

Ascending Order by Keys

Map<Integer, String> map = new HashMap<>();
map.put(5, "five");
map.put(2, "two");
map.put(8, "eight");

Map<Integer, String> sortedMap = new TreeMap<>(map);

for (Map.Entry<Integer, String> entry : sortedMap.entrySet())
System.out.println("Entry Key - " + entry.getKey() + " Entry Value - " + entry.getValue());

Ascending Order by Values

Map<Integer, String> map = new HashMap<>();
map.put(5, "five");
map.put(2, "two");
map.put(8, "eight");

List<Map.Entry<Integer, String>> entries = new ArrayList<>(map.entrySet());
entries.sort(Map.Entry.comparingByValue());

Map<Integer, String> sortedMapByValue = new LinkedHashMap<>();
for (Map.Entry<Integer, String> entry : entries) {
    sortedMapByValue.put(entry.getKey(), entry.getValue());
}

for (Map.Entry<Integer, String> entry : sortedMapByValue.entrySet()) {
    System.out.println("Entry Key - " + entry.getKey() + " Entry Value - " + entry.getValue());
}

Descending Order by Keys

Map<Integer, String> map = new HashMap<>();
map.put(5, "five");
map.put(2, "two");
map.put(8, "eight");

Map<Integer, String> sortedMap = new TreeMap<>(Collections.reverseOrder());
sortedMap.putAll(map);

for (Map.Entry<Integer, String> entry : sortedMap.entrySet()) {
    System.out.println("Entry Key - " + entry.getKey() + " Entry Value - " + entry.getValue());
}

Descending Order by Values

Map<Integer, String> map = new HashMap<>();
map.put(5, "five");
map.put(2, "two");
map.put(8, "eight");

List<Map.Entry<Integer, String>> entries = new ArrayList<>(map.entrySet());
entries.sort(Map.Entry.comparingByValue(Comparator.reverseOrder()));

Map<Integer, String> sortedMapByValue = new LinkedHashMap<>();
for (Map.Entry<Integer, String> entry : entries) {
    sortedMapByValue.put(entry.getKey(), entry.getValue());
}

for (Map.Entry<Integer, String> entry : sortedMapByValue.entrySet()) {
    System.out.println("Entry Key - " + entry.getKey() + " Entry Value - " + entry.getValue());
}

Custom Object

Person Class

class Person {
    private String id;
    private String name;
    private int age;

    public Person(String id, String name, int age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    public String getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    @Override
    public String toString() {
        return "Person{" +
                "id='" + id + '\'' +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

Ascending Order by Keys

Map<String, Person> personMap = new HashMap<>();
personMap.put("2", new Person("2", "Bob", 25));
personMap.put("1", new Person("1", "Alice", 30));
personMap.put("3", new Person("3", "Charlie", 35));

Map<String, Person> sortedByKeyMap = new TreeMap<>(personMap);

// Print sorted map
sortedByKeyMap.forEach((key, value) -> System.out.println(key + ": " + value));

Descending Order by Keys

Map<String, Person> personMap = new HashMap<>();
personMap.put("2", new Person("2", "Bob", 25));
personMap.put("1", new Person("1", "Alice", 30));
personMap.put("3", new Person("3", "Charlie", 35));

Map<String, Person> sortedByKeyDescMap = new TreeMap<>(Collections.reverseOrder());
sortedByKeyDescMap.putAll(personMap);

// Print sorted map
sortedByKeyDescMap.forEach((key, value) -> System.out.println(key + ": " + value));

Ascending Order by Values (Person's Age)

Map<String, Person> personMap = new HashMap<>();
personMap.put("2", new Person("2", "Bob", 25));
personMap.put("1", new Person("1", "Alice", 30));
personMap.put("3", new Person("3", "Charlie", 35));

List<Map.Entry<String, Person>> entries = new ArrayList<>(personMap.entrySet());
entries.sort(Map.Entry.comparingByValue(Comparator.comparingInt(Person::getAge)));

Map<String, Person> sortedByValueMap = new LinkedHashMap<>();
for (Map.Entry<String, Person> entry : entries) {
        sortedByValueMap.put(entry.getKey(), entry.getValue());
}

// Print sorted map
sortedByValueMap.forEach((key, value) -> System.out.println(key + ": " + value));

Descending Order by Values (Person's Age)

Map<String, Person> personMap = new HashMap<>();
personMap.put("2", new Person("2", "Bob", 25));
personMap.put("1", new Person("1", "Alice", 30));
personMap.put("3", new Person("3", "Charlie", 35));

List<Map.Entry<String, Person>> entries = new ArrayList<>(personMap.entrySet());
entries.sort(Map.Entry.comparingByValue(Comparator.comparingInt(Person::getAge).reversed()));

Map<String, Person> sortedByValueMap = new LinkedHashMap<>();
for (Map.Entry<String, Person> entry : entries) {
        sortedByValueMap.put(entry.getKey(), entry.getValue());
}

// Print sorted map
sortedByValueMap.forEach((key, value) -> System.out.println(key + ": " + value));

Nested List

Wrapper Primitives

Ascending Order

List<List<Integer>> nestedList = new ArrayList<>();
nestedList.add(Arrays.asList(3, 5, 4));
nestedList.add(Arrays.asList(8, 2, 6));

// Sort inner lists
for (List<Integer> list : nestedList) {
        Collections.sort(list);
}

// Sort outer list based on the first element of each inner list
nestedList.sort(Comparator.comparingInt(list -> list.get(0)));

nestedList.forEach(System.out::println);

Descending Order

List<List<Integer>> nestedList = new ArrayList<>();
nestedList.add(Arrays.asList(3, 5, 4));
nestedList.add(Arrays.asList(8, 2, 6));

// Sort inner lists in reverse order
for (List<Integer> list : nestedList) {
        Collections.sort(list, Collections.reverseOrder());
}

// Sort outer list in reverse order based on the first element of each inner list
nestedList.sort(Comparator.comparingInt((List<Integer> list) -> list.get(0)).reversed());

nestedList.forEach(System.out::println);

Custom Object

class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

Ascending Order by Age

List<List<Person>> nestedPersonList = new ArrayList<>();
nestedPersonList.add(Arrays.asList(new Person("Alice", 30), new Person("Bob", 25)));
nestedPersonList.add(Arrays.asList(new Person("Charlie", 35), new Person("Dave", 28)));

// Sort inner lists by age
for (List<Person> list : nestedPersonList) {
        list.sort(Comparator.comparingInt(Person::getAge));
}

// Sort outer list by the first person's age in each inner list
nestedPersonList.sort(Comparator.comparingInt(list -> list.get(0).getAge()));

nestedPersonList.forEach(System.out::println);

Descending Order by Age

List<List<Person>> nestedPersonList = new ArrayList<>();
nestedPersonList.add(Arrays.asList(new Person("Alice", 30), new Person("Bob", 25)));
nestedPersonList.add(Arrays.asList(new Person("Charlie", 35), new Person("Dave", 28)));

// Sort inner lists by age in reverse order
for (List<Person> list : nestedPersonList) {
        list.sort(Comparator.comparingInt(Person::getAge).reversed());
}

// Sort outer list by the first person's age in reverse order
nestedPersonList.sort(Comparator.comparingInt((List<Person> list) -> list.get(0).getAge()).reversed());

nestedPersonList.forEach(System.out::println);

Nested Map

Wrapper Primitives

Ascending Order

Map<Integer, Map<Integer, String>> nestedMap = new HashMap<>();
nestedMap.put(1, new HashMap<>(Map.of(3, "three", 1, "one", 2, "two")));
nestedMap.put(2, new HashMap<>(Map.of(6, "six", 5, "five", 4, "four")));

// Sort inner maps
for (Map.Entry<Integer, Map<Integer, String>> entry : nestedMap.entrySet()) {
        Map<Integer, String> sortedInnerMap = new TreeMap<>(entry.getValue());
        nestedMap.put(entry.getKey(), sortedInnerMap);
}

// Sort outer map
Map<Integer, Map<Integer, String>> sortedNestedMap = new TreeMap<>(nestedMap);
sortedNestedMap.forEach((key, value) -> System.out.println(STR."Key: \{key} Value: \{value}"));

Descending Order

Map<Integer, Map<Integer, String>> nestedMap = new HashMap<>();
nestedMap.put(1, new HashMap<>(Map.of(3, "three", 1, "one", 2, "two")));
nestedMap.put(2, new HashMap<>(Map.of(6, "six", 5, "five", 4, "four")));

// Sort inner maps in reverse order
for (Map.Entry<Integer, Map<Integer, String>> entry : nestedMap.entrySet()) {
    Map<Integer, String> sortedInnerMap = new TreeMap<>(Collections.reverseOrder());
    sortedInnerMap.putAll(entry.getValue());
    nestedMap.put(entry.getKey(), sortedInnerMap);
}

// Sort outer map in reverse order
Map<Integer, Map<Integer, String>> sortedNestedMap = new TreeMap<>(Collections.reverseOrder());
sortedNestedMap.putAll(nestedMap);

sortedNestedMap.forEach((key, value) -> System.out.println(STR."Key: \{key} Value: \{value}"));

Custom Object

Assuming Person as keys in nested maps.

Ascending Order

Map<Person, Map<Person, String>> nestedPersonMap = new HashMap<>();
nestedPersonMap.put(new Person("Group1", 50), new HashMap<>(Map.of(new Person("Alice", 30), "Alice", new Person("Bob", 25), "Bob")));
nestedPersonMap.put(new Person("Group2", 60), new HashMap<>(Map.of(new Person("Charlie", 35), "Charlie", new Person("Dave", 28), "Dave")));

// Sort inner maps by age
for (Map.Entry<Person, Map<Person, String>> entry : nestedPersonMap.entrySet()) {
    Map<Person, String> sortedInnerMap = new TreeMap<>(Comparator.comparingInt(Person::getAge));
    sortedInnerMap.putAll(entry.getValue());
    nestedPersonMap.put(entry.getKey(), sortedInnerMap);
}

// Sort outer map by age
Map<Person, Map<Person, String>> sortedNestedPersonMap = new TreeMap<>(Comparator.comparingInt(Person::getAge));
sortedNestedPersonMap.putAll(nestedPersonMap);

sortedNestedPersonMap.forEach((key, value) -> System.out.println(STR."Key: \{key} Value: \{value}"));

Descending Order

Map<Person, Map<Person, String>> nestedPersonMap = new HashMap<>();
nestedPersonMap.put(new Person("Group1", 50), new HashMap<>(Map.of(new Person("Alice", 30), "Alice", new Person("Bob", 25), "Bob")));
nestedPersonMap.put(new Person("Group2", 60), new HashMap<>(Map.of(new Person("Charlie", 35), "Charlie", new Person("Dave", 28), "Dave")));

// Sort inner maps by age in reverse order
for (Map.Entry<Person, Map<Person, String>> entry : nestedPersonMap.entrySet()) {
        Map<Person, String> sortedInnerMap = new TreeMap<>(Comparator.comparingInt(Person::getAge).reversed());
        sortedInnerMap.putAll(entry.getValue());
        nestedPersonMap.put(entry.getKey(), sortedInnerMap);
}

// Sort outer map by age in reverse order
Map<Person, Map<Person, String>> sortedNestedPersonMap = new TreeMap<>(Comparator.comparingInt(Person::getAge).reversed());
sortedNestedPersonMap.putAll(nestedPersonMap);

sortedNestedPersonMap.forEach((key, value) -> System.out.println(STR."Key: \{key} Value: \{value}"));

Nested Set

Since Set does not maintain order, we'll use a sorted Set implementation like TreeSet.

Wrapper Primitives

Ascending Order

Set<Set<Integer>> nestedSet = new HashSet<>();
nestedSet.add(new HashSet<>(Arrays.asList(3, 5, 1)));
nestedSet.add(new HashSet<>(Arrays.asList(8, 2, 6)));

// Sort inner sets
Set<Set<Integer>> sortedNestedSet = new TreeSet<>(Comparator.comparingInt(set -> set.iterator().next()));
for (Set<Integer> set : nestedSet) {
        sortedNestedSet.add(new TreeSet<>(set));
}

sortedNestedSet.forEach(System.out::println);

Descending Order

Set<Set<Integer>> nestedSet = new HashSet<>();
nestedSet.add(new HashSet<>(Arrays.asList(3, 5, 1)));
nestedSet.add(new HashSet<>(Arrays.asList(8, 2, 6)));

// Sort inner sets
Set<Set<Integer>> sortedNestedSet = new TreeSet<>(Comparator.comparingInt((Set<Integer> set) -> set.iterator().next()).reversed());
for (Set<Integer> set : nestedSet) {
        sortedNestedSet.add(new TreeSet<>(set).descendingSet());
}

sortedNestedSet.forEach(System.out::println);

Custom Object

Assuming Person as elements in sets.

Ascending Order

Set<Set<Person>> nestedPersonSet = new HashSet<>();
nestedPersonSet.add(new HashSet<>(Arrays.asList(new Person("Alice", 30), new Person("Bob", 25))));
nestedPersonSet.add(new HashSet<>(Arrays.asList(new Person("Charlie", 35), new Person("Dave", 28))));

// Sort inner sets by age
Set<Set<Person>> sortedNestedPersonSet = new TreeSet<>(Comparator.comparingInt(set -> set.iterator().next().getAge()));
for (Set<Person> set : nestedPersonSet) {
        Set<Person> sortedInnerSet = new TreeSet<>(Comparator.comparingInt(Person::getAge));
        sortedInnerSet.addAll(set);
        sortedNestedPersonSet.add(sortedInnerSet);
}

sortedNestedPersonSet.forEach(System.out::println);

Descending Orde

Set<Set<Person>> nestedPersonSet = new HashSet<>();
nestedPersonSet.add(new HashSet<>(Arrays.asList(new Person("Alice", 30), new Person("Bob", 25))));
nestedPersonSet.add(new HashSet<>(Arrays.asList(new Person("Charlie", 35), new Person("Dave", 28))));

// Sort inner sets by age
Set<Set<Person>> sortedNestedPersonSet = new TreeSet<>(Comparator.comparingInt((Set<Person> set) -> set.iterator().next().getAge()).reversed());
for (Set<Person> set : nestedPersonSet) {
    Set<Person> sortedInnerSet = new TreeSet<>(Comparator.comparingInt(Person::getAge).reversed());
    sortedInnerSet.addAll(set);
    sortedNestedPersonSet.add(sortedInnerSet);
}

sortedNestedPersonSet.forEach(System.out::println);

Nested List of Set

Wrapper Primitives

Ascending Order

List<Set<Integer>> nestedListSet = new ArrayList<>();
nestedListSet.add(new HashSet<>(Arrays.asList(3, 5, 1)));
nestedListSet.add(new HashSet<>(Arrays.asList(8, 2, 6)));

// Sort inner sets
List<Set<Integer>> sortedNestedListSet = new ArrayList<>();
for (Set<Integer> set : nestedListSet) {
        Set<Integer> sortedSet = new TreeSet<>(set);
        sortedNestedListSet.add(sortedSet);
}

// Sort outer list based on the first element of each inner set
sortedNestedListSet.sort(Comparator.comparingInt(set -> set.iterator().next()));

// Print sorted nested list of sets
System.out.println("Ascending Order:");
sortedNestedListSet.forEach(System.out::println);

Descending Order

List<Set<Integer>> nestedListSet = new ArrayList<>();
nestedListSet.add(new HashSet<>(Arrays.asList(3, 5, 1)));
nestedListSet.add(new HashSet<>(Arrays.asList(8, 2, 6)));

// Sort inner sets in reverse order
List<Set<Integer>> sortedNestedListSet = new ArrayList<>();
for (Set<Integer> set : nestedListSet) {
        Set<Integer> sortedSet = new TreeSet<>(Collections.reverseOrder());
        sortedSet.addAll(set);
        sortedNestedListSet.add(sortedSet);
}

// Sort outer list based on the first element of each inner set in reverse order
sortedNestedListSet.sort(Comparator.comparingInt((Set<Integer> set) -> set.iterator().next()).reversed());

// Print sorted nested list of sets
System.out.println("Descending Order:");
sortedNestedListSet.forEach(System.out::println);

Custom Objects

Person Class

class Person {
    private String id;
    private String name;
    private int age;

    public Person(String id, String name, int age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    public int getAge() {
        return age;
    }

    @Override
    public String toString() {
        return "Person{id='" + id + "', name='" + name + "', age=" + age + '}';
    }
}

Ascending Order

List<Set<Person>> nestedListSet = new ArrayList<>();
nestedListSet.add(new HashSet<>(Arrays.asList(new Person("1", "Alice", 30), new Person("2", "Bob", 25))));
nestedListSet.add(new HashSet<>(Arrays.asList(new Person("3", "Charlie", 35), new Person("4", "Dave", 28))));

// Sort inner sets by age
List<Set<Person>> sortedNestedListSet = new ArrayList<>();
for (Set<Person> set : nestedListSet) {
        Set<Person> sortedSet = new TreeSet<>(Comparator.comparingInt(Person::getAge));
        sortedSet.addAll(set);
        sortedNestedListSet.add(sortedSet);
}

// Sort outer list based on the first person's age in each inner set
sortedNestedListSet.sort(Comparator.comparingInt(set -> set.iterator().next().getAge()));

// Print sorted nested list of sets
System.out.println("Ascending Order by Age:");
sortedNestedListSet.forEach(System.out::println);

Descending Order

List<Set<Person>> nestedListSet = new ArrayList<>();
nestedListSet.add(new HashSet<>(Arrays.asList(new Person("1", "Alice", 30), new Person("2", "Bob", 25))));
nestedListSet.add(new HashSet<>(Arrays.asList(new Person("3", "Charlie", 35), new Person("4", "Dave", 28))));

// Sort inner sets by age in reverse order
List<Set<Person>> sortedNestedListSet = new ArrayList<>();
for (Set<Person> set : nestedListSet) {
        Set<Person> sortedSet = new TreeSet<>(Comparator.comparingInt(Person::getAge).reversed());
        sortedSet.addAll(set);
        sortedNestedListSet.add(sortedSet);
}

// Sort outer list based on the first person's age in each inner set in reverse order
sortedNestedListSet.sort(Comparator.comparingInt((Set<Person> set) -> set.iterator().next().getAge()).reversed());

// Print sorted nested list of sets
System.out.println("Descending Order by Age:");
sortedNestedListSet.forEach(System.out::println);

Nested List of Map

Wrapper Primitives

Ascending Order

List<Map<Integer, String>> nestedListMap = new ArrayList<>();
nestedListMap.add(new HashMap<>(Map.of(3, "three", 1, "one", 2, "two")));
nestedListMap.add(new HashMap<>(Map.of(6, "six", 5, "five", 4, "four")));

// Sort inner maps
List<Map<Integer, String>> sortedNestedListMap = new ArrayList<>();
for (Map<Integer, String> map : nestedListMap) {
        Map<Integer, String> sortedMap = new TreeMap<>(map);
        sortedNestedListMap.add(sortedMap);
}

// Sort outer list based on the first key in each inner map
sortedNestedListMap.sort(Comparator.comparingInt(map -> map.keySet().iterator().next()));

// Print sorted nested list of maps
System.out.println("Ascending Order:");
sortedNestedListMap.forEach(System.out::println);

Descending Order

List<Map<Integer, String>> nestedListMap = new ArrayList<>();
nestedListMap.add(new HashMap<>(Map.of(3, "three", 1, "one", 2, "two")));
nestedListMap.add(new HashMap<>(Map.of(6, "six", 5, "five", 4, "four")));

// Sort inner maps in reverse order
List<Map<Integer, String>> sortedNestedListMap = new ArrayList<>();
for (Map<Integer, String> map : nestedListMap) {
        Map<Integer, String> sortedMap = new TreeMap<>(Collections.reverseOrder());
        sortedMap.putAll(map);
        sortedNestedListMap.add(sortedMap);
}

// Sort outer list based on the first key in each inner map in reverse order
sortedNestedListMap.sort(Comparator.comparingInt((Map<Integer, String> map) -> map.keySet().iterator().next()).reversed());

// Print sorted nested list of maps
System.out.println("Descending Order:");
sortedNestedListMap.forEach(System.out::println);

Custom Object

Ascending Order

List<Map<String, Person>> nestedListMap = new ArrayList<>();
nestedListMap.add(new HashMap<>(Map.of("2", new Person("2", "Bob", 25), "1", new Person("1", "Alice", 30))));
nestedListMap.add(new HashMap<>(Map.of("4", new Person("4", "Dave", 28), "3", new Person("3", "Charlie", 35))));

// Sort inner maps by key
List<Map<String, Person>> sortedNestedListMap = new ArrayList<>();
for (Map<String, Person> map : nestedListMap) {
        Map<String, Person> sortedMap = new TreeMap<>(map);
        sortedNestedListMap.add(sortedMap);
}

// Sort outer list based on the first key in each inner map
sortedNestedListMap.sort(Comparator.comparing(map -> map.keySet().iterator().next()));

// Print sorted nested list of maps
System.out.println("Ascending Order by Key:");
sortedNestedListMap.forEach(System.out::println);

Descending Order

List<Map<String, Person>> nestedListMap = new ArrayList<>();
nestedListMap.add(new HashMap<>(Map.of("2", new Person("2", "Bob", 25), "1", new Person("1", "Alice", 30))));
nestedListMap.add(new HashMap<>(Map.of("4", new Person("4", "Dave", 28), "3", new Person("3", "Charlie", 35))));

// Sort inner maps by key in reverse order
List<Map<String, Person>> sortedNestedListMap = new ArrayList<>();
for (Map<String, Person> map : nestedListMap) {
        Map<String, Person> sortedMap = new TreeMap<>(Collections.reverseOrder());
        sortedMap.putAll(map);
        sortedNestedListMap.add(sortedMap);
}

// Sort outer list based on the first key in each inner map in reverse order
sortedNestedListMap.sort(Comparator.comparing((Map<String, Person> map) -> map.keySet().iterator().next()).reversed());

// Print sorted nested list of maps
System.out.println("Descending Order by Key:");
sortedNestedListMap.forEach(System.out::println);
PreviousComparator InterfaceNextInsertion Ordering

Last updated 5 months ago

Was this helpful?