jjzjj

java - 在 int 属性上按降序对自定义对象数组进行排序

coder 2024-03-22 原文

我想按出生年份降序排列我的数组。 我的数组还有两个其他类型的 String 元素。 因此,例如,出生在最早年份(例如 1939 年)的人将排在首位,然后依此类推。

这是我的代码:

import java.util.*;
public class StudentInformationTest
{
public static void main (String [] args){ 
    StudentInformation[] studentInfo = new StudentInformation[10];

    studentInfo[0] = new StudentInformation("Student A",1971, "BSc FDIT");
    studentInfo[1] = new StudentInformation("Student B",1964, "BSc FDIT"); 
    studentInfo[2] = new StudentInformation("Student C",1996, "BSc FDIT"); 
    studentInfo[3] = new StudentInformation("Student D",1939, "BSc FDIT"); 
    studentInfo[4] = new StudentInformation("Student E",1945, "BSc FDIT"); 
    studentInfo[5] = new StudentInformation("Student F",1991, "BSc FDIT"); 
    studentInfo[6] = new StudentInformation("Student G",1987, "BSc FDIT"); 
    studentInfo[7] = new StudentInformation("Student H",1968, "BSc FDIT"); 
    studentInfo[8] = new StudentInformation("Student I",1968, "BSc FDIT"); 
    studentInfo[9] = new StudentInformation("Student J",1973, "BSc FDIT"); 

    printInfo(studentInfo);
    printAge(studentInfo);
}
public static void printInfo(StudentInformation studentInfo[]){
    for(int i = 0; i < studentInfo.length; i++){
        System.out.println(studentInfo[i].getStudentName() + " " +   studentInfo[i].getBirthDate() + " " + studentInfo[i].getProgrammeOfStudy());
    }
    System.out.println();
}

 }

}

一旦我设法按降序打印出生年份,我还需要显示学生姓名和他们正在学习的大学模块。 我知道其他问题已被问到如何执行此操作,但我无法看到其他对象。 这是一个类,所以请原谅我的代码中的任何错误。

最佳答案

使用 Comparator和一个 ArrayList .

在 Java 8 中

Comparator 上使用新的默认和静态方法!

ArrayList<StudentInformation> infos = new ArrayList<StudentInformation>();
// fill array
Collections.sort(infos, 
    Comparator.comparingInt(StudentInformation::getBirthYear).reversed());

这是一个勇敢的新世界! :)

或者——仍然比 Java 7 更好——使用 lambdas !

ArrayList<StudentInformation> infos = new ArrayList<StudentInformation>();
// fill array
Collections.sort(infos, (s1, s2) ->
    Integer.compare(s2.getBirthYear(), s1.getBirthYear()));

在 Java 7 中

使用匿名内部类。

class StudentDateComparator implements Comparator<StudentInformation> {
    public int compare(StudentInformation s1, StudentInformation s2) {
        return Integer.compare(s2.getBirthYear(), s1.getBirthYear());
    }
}

ArrayList<StudentInformation> infos = new ArrayList<StudentInformation>();
// fill array
Collections.sort(infos, new StudentDateComparator());

解释

什么 Comparator做的是允许任何东西比较给定类型的两个对象(在本例中为 StudentInformation )。你也可以制作 StudentInformation实现 Comparable<StudentInformation> , 但这种方法可能更好,因为有不止一种方法可以比较学生信息(按日期,如此处,但也可以按名字、姓氏、注册类(class)数等)。

通过交换 s1 的顺序和 s2在比较器中,我们引入了相反的顺序。另一种方法是否定 compare按正常顺序调用,或使用普通比较器并将其包装在 Collections.reverseOrder 中.


您也可以使用标准数组执行此操作。

StudentInformation[] infos = new StudentInformation[10];
// fill array
Arrays.sort(infos, new StudentDateComparator());

关于java - 在 int 属性上按降序对自定义对象数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15326248/

有关java - 在 int 属性上按降序对自定义对象数组进行排序的更多相关文章

  1. ruby - 如何从 ruby​​ 中的字符串运行任意对象方法? - 2

    总的来说,我对ruby​​还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用

  2. ruby - Facter::Util::Uptime:Module 的未定义方法 get_uptime (NoMethodError) - 2

    我正在尝试设置一个puppet节点,但ruby​​gems似乎不正常。如果我通过它自己的二进制文件(/usr/lib/ruby/gems/1.8/gems/facter-1.5.8/bin/facter)在cli上运行facter,它工作正常,但如果我通过由ruby​​gems(/usr/bin/facter)安装的二进制文件,它抛出:/usr/lib/ruby/1.8/facter/uptime.rb:11:undefinedmethod`get_uptime'forFacter::Util::Uptime:Module(NoMethodError)from/usr/lib/ruby

  3. ruby-on-rails - 按天对 Mongoid 对象进行分组 - 2

    在控制台中反复尝试之后,我想到了这种方法,可以按发生日期对类似activerecord的(Mongoid)对象进行分组。我不确定这是完成此任务的最佳方法,但它确实有效。有没有人有更好的建议,或者这是一个很好的方法?#eventsisanarrayofactiverecord-likeobjectsthatincludeatimeattributeevents.map{|event|#converteventsarrayintoanarrayofhasheswiththedayofthemonthandtheevent{:number=>event.time.day,:event=>ev

  4. ruby - 将数组的内容转换为 int - 2

    我需要读入一个包含数字列表的文件。此代码读取文件并将其放入二维数组中。现在我需要获取数组中所有数字的平均值,但我需要将数组的内容更改为int。有什么想法可以将to_i方法放在哪里吗?ClassTerraindefinitializefile_name@input=IO.readlines(file_name)#readinfile@size=@input[0].to_i@land=[@size]x=1whilex 最佳答案 只需将数组映射为整数:@land边注如果你想得到一条线的平均值,你可以这样做:values=@input[x]

  5. ruby-on-rails - 如果为空或不验证数值,则使属性默认为 0 - 2

    我希望我的UserPrice模型的属性在它们为空或不验证数值时默认为0。这些属性是tax_rate、shipping_cost和price。classCreateUserPrices8,:scale=>2t.decimal:tax_rate,:precision=>8,:scale=>2t.decimal:shipping_cost,:precision=>8,:scale=>2endendend起初,我将所有3列的:default=>0放在表格中,但我不想要这样,因为它已经填充了字段,我想使用占位符。这是我的UserPrice模型:classUserPrice回答before_val

  6. ruby-on-rails - Rails 3.2.1 中 ActionMailer 中的未定义方法 'default_content_type=' - 2

    我在我的项目中添加了一个系统来重置用户密码并通过电子邮件将密码发送给他,以防他忘记密码。昨天它运行良好(当我实现它时)。当我今天尝试启动服务器时,出现以下错误。=>BootingWEBrick=>Rails3.2.1applicationstartingindevelopmentonhttp://0.0.0.0:3000=>Callwith-dtodetach=>Ctrl-CtoshutdownserverExiting/Users/vinayshenoy/.rvm/gems/ruby-1.9.3-p0/gems/actionmailer-3.2.1/lib/action_mailer

  7. ruby-on-rails - 在混合/模块中覆盖模型的属性访问器 - 2

    我有一个包含模块的模型。我想在模块中覆盖模型的访问器方法。例如:classBlah这显然行不通。有什么想法可以实现吗? 最佳答案 您的代码看起来是正确的。我们正在毫无困难地使用这个确切的模式。如果我没记错的话,Rails使用#method_missing作为属性setter,因此您的模块将优先,阻止ActiveRecord的setter。如果您正在使用ActiveSupport::Concern(参见thisblogpost),那么您的实例方法需要进入一个特殊的模块:classBlah

  8. ruby-on-rails - 如何验证非模型(甚至非对象)字段 - 2

    我有一个表单,其中有很多字段取自数组(而不是模型或对象)。我如何验证这些字段的存在?solve_problem_pathdo|f|%>... 最佳答案 创建一个简单的类来包装请求参数并使用ActiveModel::Validations。#definedsomewhere,atthesimplest:require'ostruct'classSolvetrue#youcouldevencheckthesolutionwithavalidatorvalidatedoerrors.add(:base,"WRONG!!!")unlesss

  9. ruby-on-rails - form_for 中不在模型中的自定义字段 - 2

    我想向我的Controller传递一个参数,它是一个简单的复选框,但我不知道如何在模型的form_for中引入它,这是我的观点:{:id=>'go_finance'}do|f|%>Transferirde:para:Entrada:"input",:placeholder=>"Quantofoiganho?"%>Saída:"output",:placeholder=>"Quantofoigasto?"%>Nota:我想做一个额外的复选框,但我该怎么做,模型中没有一个对象,而是一个要检查的对象,以便在Controller中创建一个ifelse,如果没有检查,请帮助我,非常感谢,谢谢

  10. ruby - 主要 :Object when running build from sublime 的未定义方法 `require_relative' - 2

    我已经从我的命令行中获得了一切,所以我可以运行rubymyfile并且它可以正常工作。但是当我尝试从sublime中运行它时,我得到了undefinedmethod`require_relative'formain:Object有人知道我的sublime设置中缺少什么吗?我正在使用OSX并安装了rvm。 最佳答案 或者,您可以只使用“require”,它应该可以正常工作。我认为“require_relative”仅适用于ruby​​1.9+ 关于ruby-主要:Objectwhenrun

随机推荐