如何基于2个属性对对象集合进行排序
我有这样的类:
static class Transactions{
private int type;
private String to;
private String from;
private double amount;
public Transactions (int type, String to, String from, double amount) {
if(type>=1 || type<=3) {
this.type=type;
this.to=to;
this.from=from;
this.amount=amount;
}
else
throw new InvalidParamaterException(type);
}
//This is for deposits and withdrawal
public Transactions (int type, String para, double amount) {
}
public int getType() {
return type;
}
public String getTo() {
return to;
}
public String getFrom() {
return from;
}
public double getAmount() {
return amount;
}
}
static class Bank {
private String Name;
private ArrayList<Customer> customers = new ArrayList<>();
private ArrayList<Company> companies = new ArrayList<>();
private ArrayList<Account> accounts = new ArrayList<>();
private String Address;
public Bank(String Name, String Address) {
this.Name=Name;
this.Address=Address;
}
public void processTransactions(Collections ts) {
Comparator<Transactions> byTypeAndTo =
Comparator.comparing(Transactions::getType)
.thenComparing(Transactions::getTo);
ts.sort(byTypeAndTo);
}
我想做的是创建 Transactions
集合,然后按 type
对该集合进行排序。键入只有值 1
, 2
, 3
,并且应按此顺序进行排序。
如果两个事务具有相同的类型,我想通过 String
属性 to (是帐号,所以它都是数字 )。
我如何对这样的两个参数进行分类?
Process Transactions()
方法应将未分类的集合作为参数,对其进行排序并处理它们。
但是最后一行的代码给出了一个错误:
The method sort(List<T>) in the type Collections is not
applicable for the arguments (Comparator<Assignment02_20190808022.Transactions>)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用
比较器的Java 8方法
接口empacting()
and :为了对对象列表进行排序,您可以在其上应用方法
sort()
,自Java 8:您可以使用此在线演示。
有关如何使用Java 8构建比较器的更多信息,请查看此 教程 。
方法签名不正确,我相信应该是:
不要将实用程序类
集合
与Collection
接口混淆,并且'省略通用类型参数。您可以仅在类型
list
的对象上调用方法sort()
(与collections.sort.sort()
相同,它期望列表和比较器)。为了对
Collection
的幌子进行排序,您需要应用铸造。由于您有一个要求您的方法应该期望类型Collection
没有其他方法的参数(但这不是很好的设计)。这就是外观:注意:最好将
bank
类中的比较器定义为公共静态最终
字段。Use Java 8 methods of the
Comparator
interfacecomparing()
andthenComparing()
:In order to sort a list of objects, you can apply method
sort()
on it, available since Java 8:You can play around with this Online demo.
For more information on how to build comparators using Java 8, have a look at this tutorial.
The method signature is incorrect, I believe it should be:
Don't confuse utility class
Collections
with theCollection
interface, and don't omit the generic type parameter.You can invoke method
sort()
only on the object of typeList
(the same withCollections.sort()
it expects a list and comparator).In order to sort the list provided in the guise of
Collection
you need to apply casting. Since you have a requirement that you method should expect an argument of typeCollection
there's no other way around it (but it's not good design). That's how it might look like:Note: it's better to define a comparator inside the
Bank
class as apublic static final
field.