-
慕田峪9158850
使用比较器:List<CustomObject> list = new ArrayList<CustomObject>();Comparator<CustomObject> comparator = new Comparator<CustomObject>() {
@Override
public int compare(CustomObject left, CustomObject right) {
return left.getId() - right.getId(); // use your logic
}};Collections.sort(list, comparator); // use the comparator as much as u wantSystem.out.println(list);另外,如果CustomObject实现Comparable,那么只需使用Collections.sort(list)使用JDK 8,语法更简单。List<CustomObject> list = getCustomObjectList();Collections.sort(list, (left, right) -> left.getId() - right.getId());System.out.println(list);更简单List<CustomObject> list = getCustomObjectList();list.sort((left, right) -> left.getId() - right.getId());System.out.println(list);简单List<CustomObject> list = getCustomObjectList();list.sort(Comparator.comparing(CustomObject::getId));System.out.println(list);显然,初始代码也可以用于JDK 8。
-
慕勒3428872
问题是:“排序集合”。所以你不能使用Collections.sort(List<T> l, Comparator<? super T> comparator)。一些技巧:对于收集类型:Comparator<String> defaultComparator = new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o1.compareTo(o2);
}};Collection<String> collection = getSomeStringCollection();String[] strings = collection.toArray(new String[collection.size()]);Arrays.sort(strings, defaultComparator);List<String> sortedStrings = Arrays.asList(strings);Collection<String> collection = getSomeStringCollection();List<String> list = new ArrayList(collection);Collections.sort(list, defaultComparator);collection = list; // if you wish对于列表类型:List<String> list = getSomeStringList();Collections.sort(list, defaultComparator);对于Set类型:Set<String> set = getSomeStringSet();// Than steps like in 'For Collection type' section or use java.util.TreeSet// TreeSet sample:// Sorted using java.lang.Comparable.Set<String> naturalSorted = new TreeSet(set);Set<String> set = getSomeStringSet();Set<String> sortedSet = new TreeSet(defaultComparator);sortedSet.addAll(set);Java 8版本。有java.util.List#sort(Comparator<? super E> c)方法List<String> list = getSomeStringList();list.sort(defaultComparator);要么List<String> list = getSomeStringList();list.sort((String o1, String o2) -> o1.compareTo(o2));或者对于实现Comparable的类型:List<String> list = getSomeStringList();list.sort(String::compareTo);
-
交互式爱情
一个稍微不同的例子说,如果你有一个类没有实现Comparable但你仍然想要在一个字段或方法上对它进行排序。Collections.sort(allMatching, new Comparator<ClassOne>() {
@Override public int compare(final ClassOne o1, final ClassOne o2) {
if (o1.getMethodToSort() > o2.getMethodToSort()) {
return 1;
} else if (o1.getMethodToSort() < o2.getMethodToSort()) {
return -1;
}
return 0;
}});