Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
java.util.Comparator in Java8
import java.util.*;
public class SortLexicographicOrder {
public static void main(String[] args) {
Person[] people = {
new Person("C", "F", 30),
new Person("B", "M", 40),
new Person("D", "M", 20),
new Person("B", "F", 40),
new Person("A", "F", 20)
};
if (true) {
// Java8
Arrays.sort(people,
Comparator.comparingInt(Person::getAge)
.thenComparing(Person::getName)
.thenComparing(Person::getGender));
} else {
// Java7
Arrays.sort(people,
new Comparator<Person>() {
@Override
public int compare(Person o1, Person o2) {
int ret;
ret = Integer.compare(o1.getAge(), o2.getAge());
if (ret != 0)
return ret;
ret = o1.getName().compareTo(o2.getName());
if (ret != 0)
return ret;
return o1.getGender().compareTo(o2.getGender());
}
});
}
for (Person e : people)
System.out.println(e);
}
}
class Person {
private final String name;
private final String gender;
private final int age;
public Person(String n, String g, int a) {
name = n;
gender = g;
age = a;
}
public String getName() { return name; }
public String getGender() { return gender; }
public int getAge() { return age; }
public String toString() {
return "{"+name+","+gender+","+age+"}";
}
}
import java.util.*;
public class SortNullable {
public static void main(String[] args) {
Item[] items = {
new Item("B", null),
new Item("A", "y"),
new Item("A", null),
new Item("A", "x"),
new Item("B", "y")
};
if (true) {
// Java8
Arrays.sort(items,
Comparator.comparing(Item::getCode)
.thenComparing(Item::getSubCode, Comparator.nullsLast(Comparator.naturalOrder())));
} else {
// Java7
Arrays.sort(items,
new Comparator<Item>() {
@Override
public int compare(Item o1, Item o2) {
int ret;
ret = o1.getCode().compareTo(o2.getCode());
if (ret != 0)
return ret;
String subCode1 = o1.getSubCode();
String subCode2 = o2.getSubCode();
if (subCode1 == null) {
if (subCode2 == null)
ret = 0; // null == null
else
ret = 1; // null > o2
} else {
if (subCode2 == null)
ret = -1; // o1 < null
else
ret = subCode1.compareTo(subCode2);
}
return ret;
}
});
}
for (Item e : items)
System.out.println(e);
}
}
class Item {
private final String code;
private final String subCode;
public Item(String c, String sc) {
code = c;
subCode = sc;
}
public String getCode() { return code; }
public String getSubCode() { return subCode; }
public String toString() {
return "{"+code+","+subCode+"}";
}
}
import java.util.*;
public class SortReverse {
public static void main(String[] args) {
String[] a = {"D", "B", "A", "C"};
if (true) {
// Java8
Arrays.sort(a, Comparator.reverseOrder());
} else {
// Java7
Arrays.sort(a,
new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o2.compareTo(o1);
}
});
}
for (String e : a)
System.out.println(e);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment