对象List根据数组排序
package com.test;
import com.app.dclzhq.model.Family;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* 自定义排序测试
* Created by MJ·J on 2019-12-03
*/
public class Demo {
public static void main(String[] args) {
String[] arr=new String[]{"张三", "李四", "王五", "马六"};
List<String> orderRegulation = Arrays.asList(arr);
List<Family> targetList = new ArrayList<Family>();
Family family = new Family();
family.setApplyPersonName("马六");
Family family2 = new Family();
family2.setApplyPersonName("张三");
Family family3 = new Family();
family3.setApplyPersonName("张三");
Family family4 = new Family();
family4.setApplyPersonName("李四");
Family family5 = new Family();
family5.setApplyPersonName("测试");
Family family6 = new Family();
family6.setApplyPersonName("王五");
targetList.add(family);
targetList.add(family2);
targetList.add(family3);
targetList.add(family4);
targetList.add(family5);
targetList.add(family6);
System.out.println("排列前的数据:");
targetList.forEach(t -> System.out.print(t.getApplyPersonName()));
System.out.println();
setListOrder(orderRegulation, targetList);
System.out.println("排序的规则:");
orderRegulation.forEach(t -> System.out.print(t + " "));
System.out.println();
System.out.println("排列后的数据:");
targetList.forEach(t -> System.out.print(t.getApplyPersonName()));
}
//平时排序可使用其中一种,下面是综合两个条件排序
public static void setListOrder(List<String> orderRegulation, List<Family> targetList) {
Collections.sort(targetList, ((o1, o2) -> {
int io1 = orderRegulation.indexOf(o1.getApplyPersonName());
int io2 = orderRegulation.indexOf(o2.getApplyPersonName());
if (io1 != -1) {
io1 = targetList.size() - io1;
}
if (io2 != -1) {
io2 = targetList.size() - io2;
}
return io2 - io1;
}));
}
}
`