Can I sort by different criteria?

Yes, you can sort by different criteria in Java using the Comparable and Comparator interfaces.

Sorting with Comparable

If you want to sort objects of a class based on a single criterion, you can implement the Comparable interface in that class. For example:

class Student implements Comparable<Student> {
    String name;
    int age;

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

    @Override
    public int compareTo(Student other) {
        return this.age - other.age; // Sort by age
    }
}

Sorting with Comparator

If you need to sort by multiple criteria or different criteria, you can use the Comparator interface. For example:

import java.util.*;

class Student {
    String name;
    int age;

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

class SortByName implements Comparator<Student> {
    public int compare(Student a, Student b) {
        return a.name.compareTo(b.name); // Sort by name
    }
}

class SortByAge implements Comparator<Student> {
    public int compare(Student a, Student b) {
        return a.age - b.age; // Sort by age
    }
}

// Usage
List<Student> students = new ArrayList<>();
students.add(new Student("Alice", 22));
students.add(new Student("Bob", 20));

// Sort by name
Collections.sort(students, new SortByName());

// Sort by age
Collections.sort(students, new SortByAge());

You can create different Comparator implementations to sort by various criteria as needed.

0 Comments

no data
Be the first to share your comment!