public class Person {
private String name;
private Integer age;
public Person(){}
public Person(String name, Integer age) {
this.name = name;
this.age = age;
}
public static int compare(Person a ,Person b) {
int r = a.getAge().compareTo(b.getAge());
if (r != 0) {
return r;
} else {
return a.getName().compareTo(b.getName());
}
}
public static int compare(Person a ,Person b,Person c) {
return 0;
}
public Person concat(Person b){
this.setName(this.getName()+","+b.getName());
System.out.println(this);
return this;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + 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 class MrTestCase {
@Test
public void case1(){
ArrayList<Person> personList = new ArrayList<>();
personList.add(new Person("Sam",20));
personList.add(new Person("Lily",23));
personList.add(new Person("Jack",20));
/* personList.sort(new Comparator<Person>() {
@Override
public int compare(Person a, Person b) {
return Person.compare(a,b);
}
});
personList.sort((a,b)->Person.compare(a,b));*/
//方法引用写法 调用static静态方法,参数类型动态推断
personList.sort(Person::compare);
System.out.println(personList);
}
@Test
public void case2(){
ArrayList<Person> personList = new ArrayList<>();
personList.add(new Person("Sam",20));
personList.add(new Person("Lily",23));
personList.add(new Person("Jack",20));
personList.stream().sorted((a,b)->Person.compare(a,b)).forEach(person -> System.out.println(person));
personList.stream().sorted(Person::compare).forEach(System.out::println);
}
@Test
public void case3(){
ArrayList<Person> personList = new ArrayList<>();
personList.add(new Person("Sam",20));
personList.add(new Person("Lily",23));
personList.add(new Person("Jack",20));
Person p = new Person("zhangsan", 0);
personList.stream().sorted(Person::compare).forEach(p::concat);
}
//::实例化对象
@Test
public void case4() {
ArrayList<Person> personList = new ArrayList<>();
personList.add(new Person("Sam", 20));
personList.add(new Person("Lily", 23));
personList.add(new Person("Jack", 20));
Person p = new Person("老六", 0);
//personList.stream().sorted(Person::compare).collect(Collectors.toList());
personList.stream().sorted(Person::compare).collect(Collectors.toCollection(ArrayList::new));
}
@Test
public void case5() {
String[] arr={"Barbara","James","Mary","John","Patricia","Robert","Michael","Linda"};
/* Arrays.sort(arr, new Comparator<String>() {
@Override
public int compare(String a, String b) {
return a.compareToIgnoreCase(b);
}
});
Arrays.sort(arr,(a,b)->a.compareToIgnoreCase(b));*/
//Arrays.sort(arr,String::compareTo);
Arrays.sort(arr,String::compareToIgnoreCase);
System.out.println(Arrays.toString(arr));
}
}