Created
June 5, 2017 06:05
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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