首页 > 代码库 > 数组转换为集合进行排序,集合、数组自定义排序

数组转换为集合进行排序,集合、数组自定义排序

数组转换成集合,sort方法进行排序
Integer[] nums = { 23, 16, 12, 58, 11 };
// 集合转换为数组
List<Integer> numList = Arrays.asList(nums);
Collections.sort(numList);
// 排序之后
for (Integer num : numList) {
    System.out.print(num + "\t");
}

 

自定义排序,实现倒序排列——内部类
Integer[] nums = { 23, 16, 12, 58, 11 };
List<Integer> numList = Arrays.asList(nums);
// 内部类排序——Comparator
final boolean mark = false;
Collections.sort(numList, new Comparator<Integer>() {
    @Override
    public int compare(Integer o1, Integer o2) {
        return mark ? o1 - o2 : o2 - o1;
    }
});
// 排序之后
for (Integer j : numList) {
    System.out.print(j + "\t");
}

 

通过Comparator接口实现对象自定义排序
import java.util.Comparator;
public class ObjectComparator implements Comparator {

    private boolean mark = true;
    private double radix= 2;
    //构造函数,set getter
    
    public ObjectComparator(boolean mark) {
        this.mark = mark;
    }
    
    public ObjectComparator(boolean mark,double radix) {
        this.mark = mark;
        this.radix = radix;
    }

    @Override
    public int compare(Object o1, Object o2) { 
        if(o1  instanceof Integer) {
            Integer a=(Integer) o1;
            Integer b=(Integer) o2;
            return mark?a-b:b-a;
        }else if(o1  instanceof Float) {
            int a=(int) (Float.parseFloat(String.valueOf(o1))*Math.pow(10,radix));
            int b=(int) (Float.parseFloat(String.valueOf(o2))*Math.pow(10,radix));
            return mark?a-b:b-a;
        }else if(o1  instanceof Double) {
            int a=(int) (Double.parseDouble(String.valueOf(o1))*Math.pow(10,radix));
            int b=(int) (Double.parseDouble(String.valueOf(o2))*Math.pow(10,radix));
            return mark?a-b:b-a;
        }else if(o1 instanceof Character){
            Character ca = (Character)o1;
            Character cb = (Character)o2;
            int a = (int)ca;
            int b = (int)cb;
            return mark?a-b:b-a;
        }
        return 0;
    }
}

 

通过Comparator接口实现日期排序
import java.util.Comparator;
import java.util.Date;

public class DateComparator implements Comparator<Date> {

    private boolean flag;

    public DateComparator() {
        flag = true;
    }

    public DateComparator(boolean flag) {
        this.flag = flag;
    }

    @Override
    public int compare(Date o1, Date o2) {
        if (this.flag) {
            if (o2.before(o1)) {// 晚于
                return -1;
            } else {
                return 1;
            }
        } else {
            if (o2.after(o1)) {// 晚于
                return -1;
            } else {
                return 1;
            }
        }
    }
}

 

数组转换为集合进行排序,集合、数组自定义排序