Java List对象中某一个值按照ListLong里的顺序进行排序
要按照List
首先,创建一个Comparator接口的实现类,用来比较List
import java.util.Comparator;
import java.util.List;
public class LongComparator implements Comparator<Long> {
private List<Long> orderList;
public LongComparator(List<Long> orderList) {
this.orderList = orderList;
}
@Override
public int compare(Long o1, Long o2) {
int index1 = orderList.indexOf(o1);
int index2 = orderList.indexOf(o2);
return Integer.compare(index1, index2);
}
}
然后,在需要排序的List对象中,调用Collections.sort()方法并传入自定义的Comparator对象:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Long> orderList = Arrays.asList(3L, 1L, 4L, 2L);
List<Long> listToSort = new ArrayList<>(Arrays.asList(1L, 2L, 3L, 4L));
Collections.sort(listToSort, new LongComparator(orderList));
System.out.println(listToSort);
}
}
上述代码中,orderList是按照需要排序的值的顺序创建的List
原文地址: https://www.cveoy.top/t/topic/iqGy 著作权归作者所有。请勿转载和采集!