需求说明
已知一个数组,需要将这个数组排序,排序的规则是:按照数组中的元素的某个属性,按照指定的顺序来排序
例如:一个包含Student的学生数组,Student中有一个分组的属性,我们要按照分组,且按照我们指定的顺序来排序
实现
实现方式是试用indexOf查找这个属性在给定的顺序数组中的位置,根据未知的大小来排序,示例如下:
public static void main(String[] args) throws Exception {
List<Student> students = new ArrayList<>();
students.add(new Student("张三", "超人组"));
students.add(new Student("李四", "蜘蛛侠组"));
students.add(new Student("王五", "钢铁侠组"));
List<String> specificGroups = List.of("蜘蛛侠组", "钢铁侠组", "超人组"); // 按照这个特定的顺序来排序
students.sort(Comparator.comparingInt(o -> specificGroups.contains(o.getGroup()) ? specificGroups.indexOf(o.getGroup()) : Integer.MAX_VALUE));
}
static class Student {
private String name;
private String group;
public Student(String name, String group) {
this.name = name;
this.group = group;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGroup() {
return group;
}
public void setGroup(String group) {
this.group = group;
}
}
public static void main(String[] args) throws Exception {
List<Student> students = new ArrayList<>();
students.add(new Student("张三", "超人组"));
students.add(new Student("李四", "蜘蛛侠组"));
students.add(new Student("王五", "钢铁侠组"));
List<String> specificGroups = List.of("蜘蛛侠组", "钢铁侠组", "超人组"); // 按照这个特定的顺序来排序
students.sort(Comparator.comparingInt(o -> specificGroups.contains(o.getGroup()) ? specificGroups.indexOf(o.getGroup()) : Integer.MAX_VALUE));
}
static class Student {
private String name;
private String group;
public Student(String name, String group) {
this.name = name;
this.group = group;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGroup() {
return group;
}
public void setGroup(String group) {
this.group = group;
}
}
public static void main(String[] args) throws Exception { List<Student> students = new ArrayList<>(); students.add(new Student("张三", "超人组")); students.add(new Student("李四", "蜘蛛侠组")); students.add(new Student("王五", "钢铁侠组")); List<String> specificGroups = List.of("蜘蛛侠组", "钢铁侠组", "超人组"); // 按照这个特定的顺序来排序 students.sort(Comparator.comparingInt(o -> specificGroups.contains(o.getGroup()) ? specificGroups.indexOf(o.getGroup()) : Integer.MAX_VALUE)); } static class Student { private String name; private String group; public Student(String name, String group) { this.name = name; this.group = group; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getGroup() { return group; } public void setGroup(String group) { this.group = group; } }
文章评论