java comparator
javaIn Java, the Comparator interface is used to compare objects of a specific type. It provides a way to define a custom ordering for a particular class, rather than using the default ordering provided by the class itself.
Here is an example of how to use the Comparator interface to define a custom comparison function for a Person class:
import java.util.Comparator;
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;
}
}
class AgeComparator implements Comparator<Person> {
@Override
public int compare(Person p1, Person p2) {
return p1.getAge() - p2.getAge();
}
}
class NameComparator implements Comparator<Person> {
@Override
public int compare(Person p1, Person p2) {
return p1.getName().compareTo(p2.getName());
}
}
In this example, we have defined two comparator classes: AgeComparator and NameComparator. The AgeComparator class compares two Person objects based on their age, and the NameComparator class compares them based on their name.
You can use these comparator classes to sort a list of Person objects in a specific order. For example:
List<Person> people = Arrays.asList(
new Person("Alice", 30),
new Person("Bob", 25),
new Person("Charlie", 35)
);
Collections.sort(people, new AgeComparator());
This will sort the list of Person objects in ascending order by age. To sort the list in descending order, you can use the Collections.reverseOrder method:
Collections.sort(people, Collections.reverseOrder(new AgeComparator()));
You can also use the Comparator.comparing method to create a comparator using a lambda expression:
Collections.sort(people, Comparator.comparing(Person::getAge));
Other Article on Tag java
- - after and before in java date
- - am pm java date format
- - apk minecraft java edition
- - as been blocked by CORS policy Response to preflight request doesn't pass access control check It does not have HTTP ok status
- - bubble sort in java
- - Can I compile and run a spring boot jar from inside another spring boot application
- - convert java date to localdate
- - design patterns in java
- - encrypt by java and decrypt by node
- - exception handling in java