Skip to content

Instantly share code, notes, and snippets.

@nfrankel
Last active July 26, 2020 21:10
Show Gist options
  • Save nfrankel/4943064682109446603987669b0b1463 to your computer and use it in GitHub Desktop.
Save nfrankel/4943064682109446603987669b0b1463 to your computer and use it in GitHub Desktop.
Sorting
import java.util.*;
public class Main {
public static class Foo implements Comparable<Foo> {
private final int value;
public Foo(int value) {
this.value = value;
}
@Override
public int compareTo(Foo foo) {
return value - foo.value;
}
@Override
public String toString() {
return "Foo(" + value + ")";
}
}
public static void main(String[] args) {
Comparator<Foo> comp = (foo1, foo2) -> {
Comparator<Foo> comp = (foo1, foo2) -> {
if (foo1 == null && foo2 == null) return 0;
if (foo1 == null) return -1;
if (foo2 == null) return 1;
return foo1.compareTo(foo2);
};
List<Foo> foos = new ArrayList<>();
foos.add(null);
for (int i = 0; i < 10; i++) {
foos.add(new Foo(i));
}
foos.add(null);
foos.add(null);
foos.add(3, null);
foos.add(10, null);
foos.sort(comp);
System.out.println(foos);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment