要按照List里的顺序对Java List对象中的某一个值进行排序,可以使用Collections.sort()方法和Comparator接口来实现。

首先,创建一个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对象。listToSort是要排序的List对象,按照orderList中的顺序进行排序后,输出结果为[3, 1, 4, 2]

Java List对象中某一个值按照ListLong里的顺序进行排序

原文地址: https://www.cveoy.top/t/topic/iqGy 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录