Skip to content

Instantly share code, notes, and snippets.

Created June 5, 2017 06:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/b7361b54a68afe154f9a4eb01ad0e228 to your computer and use it in GitHub Desktop.
Save anonymous/b7361b54a68afe154f9a4eb01ad0e228 to your computer and use it in GitHub Desktop.
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
public class Foo {
private static class Person {
private int age;
private String name;
Person(int age, String name) {
this.age = age;
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return name + ": " + age;
}
}
private static void sortByAgeA(List<Person> people) {
people.sort(new Comparator<Person>() {
@Override
public int compare(Person a, Person b) {
if (a.age == b.age) {
return 0;
}
return a.age > b.age ? 1 : -1;
}
});
}
private static void sortByAgeB(List<Person> people) {
people.sort(Comparator.comparingInt(person -> person.age));
}
public static void main(String[] args) {
List<Person> people = Arrays.asList(
new Person(20, "A"),
new Person(18, "B"),
new Person(22, "C")
);
sortByAgeA(people);
System.out.println(Arrays.deepToString(people.toArray()));
people = Arrays.asList(
new Person(20, "A"),
new Person(18, "B"),
new Person(22, "C")
);
sortByAgeB(people);
System.out.println(Arrays.deepToString(people.toArray()));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment