zoukankan      html  css  js  c++  java
  • java 18-11 Collections用于ArrayList集合中

      Collections可以针对ArrayList存储基本包装类的元素排序,存储自定义对象可不可以排序呢?
        自定义对象要自己写比较器进行排序

     1 package cn.itcast_02;
     2 
     3 import java.util.ArrayList;
     4 import java.util.Collections;
     5 import java.util.Comparator;
     6 import java.util.List;
     7 public class CollectionsDemo {
     8     public static void main(String[] args) {
     9         // 创建集合对象
    10         List<Student> list = new ArrayList<Student>();
    11 
    12         // 创建学生对象
    13         Student s1 = new Student("林青霞", 27);
    14         Student s2 = new Student("风清扬", 30);
    15         Student s3 = new Student("刘晓曲", 28);
    16         Student s4 = new Student("武鑫", 29);
    17         Student s5 = new Student("林青霞", 27);
    18 
    19         // 添加元素对象
    20         list.add(s1);
    21         list.add(s2);
    22         list.add(s3);
    23         list.add(s4);
    24         list.add(s5);
    25 
    26         // 排序
    27         // 自然排序
    28         // Collections.sort(list);
    29         // 比较器排序
    30         // 如果同时有自然排序和比较器排序,以比较器排序为主
    31         Collections.sort(list, new Comparator<Student>() {
    32             @Override
    33             public int compare(Student s1, Student s2) {
    34                 int num = s2.getAge() - s1.getAge();
    35                 int num2 = num == 0 ? s1.getName().compareTo(s2.getName())
    36                         : num;
    37                 return num2;
    38             }
    39         });
    40 
    41         // 遍历集合
    42         for (Student s : list) {
    43             System.out.println(s.getName() + "---" + s.getAge());
    44         }
    45     }
    46 }
    何事都只需坚持.. 难? 维熟尔。 LZL的自学历程...只需坚持
  • 相关阅读:
    python 序列排序 排序后返回相应的索引
    海明距离
    hive学习01词频统计
    自然语言处理之LCS最长公共子子序列
    自然语言处理之关键词提取TF-IDF
    自然语言处理之比较两个句子的相似度 余弦相似度
    linux命令tar压缩解压
    linux学习之软件包安装
    集群间数据迁移报错
    hive学习04-员工部门表综合案例
  • 原文地址:https://www.cnblogs.com/LZL-student/p/5910142.html
Copyright © 2011-2022 走看看