import java.util.Collections;import java.util.List;import java.util.ArrayList;import java.util.Comparator; public class JavaTest { public static void main(String args[]){ Listnames2 = new ArrayList (); names2.add("Taobaoa "); names2.add("Taobaoc "); names2.add("Taobaob "); JavaTest tester = new JavaTest(); tester.sortUsingJava8(names2); System.out.println(names2); Person p1 = new Person(); p1.setName("hhh"); Person p2 = new Person(); p2.setName("bbb"); List list = new ArrayList (); list.add(p1); list.add(p2); tester.sortUsingJava82(list); System.out.println(list); } // 使用 java 7 排序 private void sortUsingJava7(List names){ Collections.sort(names, new Comparator () { @Override public int compare(String s1, String s2) { return s2.compareTo(s1); } }); } // 使用 java 8 排序 private void sortUsingJava8(List names){ Collections.sort(names, (s1, s2) -> s1.compareTo(s2)); } private void sortUsingJava82(List list){ Collections.sort(list, (s1, s2) -> s1.getName().compareTo(s2.getName())); }}
/** * @author lcy * @DATE 2018/5/23 */public class Person { private String name; private String homeAddress; private Integer age; public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public String getHomeAddress() { return homeAddress; } public void setHomeAddress(String homeAddress) { this.homeAddress = homeAddress; } @Override public String toString() { return "Person{" + "name='" + name + '\'' + ", homeAddress='" + homeAddress + '\'' + ", age=" + age + '}'; }}