Created
February 24, 2014 18:40
-
-
Save tuxdna/9194243 to your computer and use it in GitHub Desktop.
simple comparator example
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
package oop; | |
class Person { | |
int age; | |
String name; | |
public Person() { | |
age = 0; // just born | |
name = "new-born"; | |
} | |
public Person(int a, String n) { | |
age = a; | |
name = n; | |
} | |
@Override | |
public String toString() { | |
return String.format("Person(%d, %s)", age, name); | |
} | |
} | |
package oop; | |
import java.util.Collections; | |
import java.util.Comparator; | |
import java.util.List; | |
import scala.actors.threadpool.Arrays; | |
public class OOPExamples { | |
public static void main(String[] args) { | |
Person[] persons = { new Person(2, "amar"), new Person(3, "akbar"), | |
new Person(), new Person(1, "anthony") | |
}; | |
List<Person> list = Arrays.asList(persons); | |
System.out.println(list); | |
Collections.sort(list, new Comparator<Person>() { | |
@Override | |
public int compare(Person o1, Person o2) { | |
return o1.age - o2.age; | |
} | |
}); | |
System.out.println(list); | |
Collections.sort(list, new Comparator<Person>() { | |
@Override | |
public int compare(Person o1, Person o2) { | |
return o1.name.compareTo(o2.name); | |
} | |
}); | |
System.out.println(list); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment