packagecom.fyb.test;importjava.util.ArrayList;importjava.util.Arrays;importjava.util.Collections;importjava.util.Comparator;importjava.util.List;importjava.util.ListIterator;public classListSortTest {public static voidmain(String[] args) {
List list = new ArrayList();
list.add("004");
list.add("002");
list.add("003");
list.add("001");//字符串测试
Arrays.asList(list.toArray(new String[0])).sort(String.CASE_INSENSITIVE_ORDER.reversed());
printList(list);//listIterator测试
ListIterator ls =list.listIterator();while(ls.hasNext()){
System.out.println(ls.next());
}
List listConsumer = new ArrayList(3);
listConsumer.add(new Consumer(1, "13838381438"));
listConsumer.add(new Consumer(3, "13838381439"));
listConsumer.add(new Consumer(2, "13838381440"));
List listConsumerTmp =cloneList(listConsumer);//Lambda表达式
listConsumerTmp.sort((final Consumer c1, final Consumer c2)->c1.getId().compareTo(c2.getId()));
printList(listConsumerTmp);//没有类型定义的Lambda表达式
listConsumerTmp =cloneList(listConsumer);
listConsumerTmp.sort((c1, c2)->c1.getId().compareTo(c2.getId()));
printList(listConsumerTmp);//使用静态方法的引用
listConsumerTmp =cloneList(listConsumer);
listConsumerTmp.sort(Consumer::compareById);
printList(listConsumerTmp);//使用静态方法的引用 (这种方式编译通过,运行报错,待找原因)
listConsumerTmp =cloneList(listConsumer);
Collections.sort(listConsumerTmp, Comparator.comparing(Consumer::getMobile));
printList(listConsumerTmp);
}/*** 打印list
*@paramlist*/
public static void printList(Listlist){
System.out.println("********* printList ************");//迭代器列表
list.stream().forEach((ls)->{
System.out.println(ls);
});
}public static List cloneList(Listlist){
List cloneList = new ArrayList(list.size());
ListIterator lts =list.listIterator();while(lts.hasNext()){
cloneList.add(lts.next());
}returncloneList;
}/*** 客户
*@authorfybing
**/
public static classConsumer{privateInteger id;privateString mobile;publicConsumer(Integer id, String mobile){this.id =id;this.mobile =mobile;
}publicInteger getId() {returnid;
}public voidsetId(Integer id) {this.id =id;
}publicString getMobile() {returnmobile;
}public voidsetMobile(String mobile) {this.mobile =mobile;
}
@OverridepublicString toString() {return "id="+id+";mobile="+mobile;
}
@Overrideprotected Consumer clone() throwsCloneNotSupportedException {
Consumer consumer= null;try{
consumer= (Consumer)super.clone();
}catch(CloneNotSupportedException e){
e.printStackTrace();
}returnconsumer;
}public static intcompareById(Consumer c1, Consumer c2){if(c1.getId() >c2.getId()){return -1;
}else if(c1.getId() ==c2.getId()){return 0;
}return -0;
}
}
}