Java排序算法Collections.sort
package com.example.core.mydemo.javaDemo; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; public class CustomSortExample { public static void main(String[] args) { List<String> list = new ArrayList<>(); list.add("cherry"); list.add("durian"); list.add("apple"); list.add("banana"); list.add("a"); System.out.println("排序前:" + list); // Collections.sort(list); //倒序 // Collections.sort(list, Comparator.reverseOrder()); //[a, apple, banana, cherry, durian] // Collections.sort(list, (s1, s2) -> s1.compareTo(s2)); //[a, apple, banana, cherry, durian] // Collections.sort(list, Comparator.naturalOrder()); //[banana, cherry, durian, a, apple] // Collections.sort(list, Comparator.comparingInt(String::hashCode)); //[a, apple, banana, cherry, durian] Collections.sort(list, Comparator.comparing(s -> s)); System.out.println("排序后:" + list); // 使用自定义Comparator进行排序 Collections.sort(list, new LengthComparator()); System.out.println("排序后2:" + list); } } class LengthComparator implements Comparator<String> { @Override public int compare(String s1, String s2) { // return s1.length() - s2.length(); //[a, apple, cherry, durian, banana] // return s1.charAt(0) - s2.charAt(0); //[apple, a, banana, cherry, durian] return s1.hashCode() - s2.hashCode(); //[banana, cherry, durian, a, apple] } }
标签:sort,Java,apple,cherry,list,Collections,durian From: https://www.cnblogs.com/oktokeep/p/18563455