Skip to content

Instantly share code, notes, and snippets.

@szhu
Last active February 11, 2016 19:44
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 szhu/1d31f2eb94515ab04429 to your computer and use it in GitHub Desktop.
Save szhu/1d31f2eb94515ab04429 to your computer and use it in GitHub Desktop.
class Animal:
def __init__(self, name, age):
self.name = name
self.age = age
def __repr__(self):
return self.name
animals = [
Animal("t-rex", 3e6),
Animal("dog", 5),
Animal("cat", 6),
Animal("ostrichhhhhhhhh", 16),
]
def minus_these_two(a1, a2):
return a1.age - a2.age
def sort_by_this(animal):
return animal.age
animals.sort(key=sort_by_this)
print animals
import java.util.*;
class Animal { // implements Comparable<Animal> {
public String name;
public int age;
public Animal(String name, int age) {
this.name = name;
this.age = age;
}
public String toString() {
return this.name;
}
// @Override
// public int compareTo(Animal o) {
// return this.age - o.age;
// }
}
class AnimalComparatorAge implements Comparator<Animal> {
@Override
public int compare(Animal a1, Animal a2) {
return a1.age - a2.age;
}
}
public class HigherOrderFunctionsTest {
public static void main(String[] args) {
ArrayList<Animal> animals = new ArrayList<Animal>();
for (Animal animal : new Animal[] {
new Animal("t-rex", 3000000),
new Animal("dog", 5),
new Animal("cat", 6),
new Animal("ostrichhhhhhhhh", 16),
}) {
animals.add(animal);
}
Collections.sort(animals, new AnimalComparatorAge());
System.out.println(animals);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment