集合习题分数排序

创建一个学生类,属性包括id[1-40],分数0-100,所有属性随机生成,创建set集合,保存20个对象,找到分数最高和分数最低的学生

private static void demo2() {
        //用treeset来做,需要提供比较器
        TreeSet<Student> students=
            new TreeSet<>(Comparator.comparing(Student::getScore));
        ThreadLocalRandom random=ThreadLocalRandom.current();//获取随机数实例
        //分数相同treeset会舍去,因此这里循环的终止点为它的长度为20
    while (students.size()<20){
      students.add(new Student(random.nextInt(20),random.nextInt(0,100)));
   }
    System.out.println(students.first()+" "+students.last());
        //但是上面做法会出现学生学号有重复值的情况,且treeset是比较慢的,我们换用下面的方法
        //用hashset来做,需要重写equals和hashcode保证元素的唯一性,但是分数是可以不用唯一的,因此只需要提供学号的重写
        Set<Student> hashSet=new HashSet<>();
        while (hashSet.size()<20){
            hashSet.add(new Student(random.nextInt(20),random.nextInt(0,100)));
        }
        hashSet.forEach(System.out::println);//id是唯一的
    //用集合的工具类来获取
        Collections.max(hashSet,Comparator.comparing(Student::getScore));
        Collections.min(hashSet,Comparator.comparing(Student::getScore));
        List<Student> collect = hashSet.parallelStream().sorted(Comparator.comparing(Student::getScore)).collect(Collectors.toList());//用stream来排序
        System.out.println(collect.get(0)+" "+collect.get(19));
    }

或者在学生类里面重写comparable接口里面的compareTo方法:

public class Student implements Comparable {
    private Integer id;
    private Integer score;

    @Override
    public int compareTo(Object student) {
        Student student1=(Student) student;
        return this.getScore()>student1.getScore()?1:(this.getScore()==student1.getScore())?0:-1;
    }

    @Override
    public boolean equals(Object object) {
        if (this == object) return true;
        if (object == null || getClass() != object.getClass()) return false;
        Student student = (Student) object;
        return Objects.equals(id, student.id) ;
    }

    @Override
    public int hashCode() {

        return Objects.hash(id);
    }
}

因为工具类里面的排序方法Collections.sort() 底层是这样说的:

/**
 * Sorts the specified list into ascending order, according to the
 * {@linkplain Comparable natural ordering} of its elements.
 * All elements in the list must implement the {@link Comparable}
 * interface.  Furthermore, all elements in the list must be
 * <i>mutually comparable</i> (that is, {@code e1.compareTo(e2)}
 * must not throw a {@code ClassCastException} for any elements
 * {@code e1} and {@code e2} in the list).
 *
 * <p>This sort is guaranteed to be <i>stable</i>:  equal elements will
 * not be reordered as a result of the sort.
 *
 * <p>The specified list must be modifiable, but need not be resizable.
 *
 * @implNote
 * This implementation defers to the {@link List#sort(Comparator)}
 * method using the specified list and a {@code null} comparator.
 *
 * @param  <T> the class of the objects in the list
 * @param  list the list to be sorted.
 * @throws ClassCastException if the list contains elements that are not
 *         <i>mutually comparable</i> (for example, strings and integers).
 * @throws UnsupportedOperationException if the specified list's
 *         list-iterator does not support the {@code set} operation.
 * @throws IllegalArgumentException (optional) if the implementation
 *         detects that the natural ordering of the list elements is
 *         found to violate the {@link Comparable} contract
 * @see List#sort(Comparator)
 */
@SuppressWarnings("unchecked")
public static <T extends Comparable<? super T>> void sort(List<T> list) {
    list.sort(null);
}
posted @ 2022-11-29 22:13  Liku007  阅读(26)  评论(0编辑  收藏  举报