Skip to content

Instantly share code, notes, and snippets.

@nhojpatrick
Last active September 1, 2018 13:11
Show Gist options
  • Save nhojpatrick/f45f6d974dd98677fca2f6abae5a9d89 to your computer and use it in GitHub Desktop.
Save nhojpatrick/f45f6d974dd98677fca2f6abae5a9d89 to your computer and use it in GitHub Desktop.
RajR.java
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class RajR {
public static class Person {
private final String firstname;
private final String surname;
private final int age;
private final String sex;
public Person(String firstname, String surname, int age, String sex) {
this.firstname = firstname;
this.surname = surname;
this.age = age;
this.sex = sex;
}
public int getAge() {
return this.age;
}
public String toString() {
return String.format("Person firstname=%s, surname=%s, age=%s, sex=%s.", this.firstname, this.surname, this.age, this.sex);
}
}
public static class AgeComparator implements Comparator<Person> {
@Override
public int compare(Person p1, Person p2) {
return Integer.compare(p1.getAge(), p2.getAge());
}
}
public static void main(final String[] args) {
final List<Person> peopleList = new ArrayList<Person>();
peopleList.add(new Person ( "Raj","R",22,"M"));
peopleList.add(new Person ( "Leo","Messi",18,"M"));
peopleList.add(new Person ( "Cr7","Ronaldo",40,"M"));
peopleList.add(new Person ( "A","Jr",60,"F"));
peopleList.add(new Person ( "B","Jr",70,"F"));
peopleList.add(new Person ( "C","Jr",80,"F"));
peopleList.add(new Person ( "D","Jr",90,"F"));
System.out.println("List Before Sort");
for (final Person p : peopleList) {
System.out.println(p);
}
Collections.sort(peopleList, new AgeComparator());
System.out.println("List After Sort");
for (final Person p : peopleList) {
System.out.println(p);
}
System.out.println("Youngest = " + peopleList.get(0));
System.out.println("Oldest = " + peopleList.get(peopleList.size() - 1));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment