[英]Sort and associate objects with unique identifier in a collection
I'm working my through an assignment and got stuck on step 5, would appreciate any help.我正在完成一项任务并卡在第 5 步,不胜感激。
Here is what I have for Q5这是我为 Q5 准备的
public abstract class OrderProcessor<T> {
private ArrayList<T> dataCollection = new ArrayList<T>();
public void accept(T item){
dataCollection.add(item);
}
public void process(){
Collections.sort(dataCollection);
}
public List getDataCollection(){
return dataCollection;
}
}
In its current state Collections.sort(dataCollection);
在其当前 state
Collections.sort(dataCollection);
doesn't compile because it does not accept T
and if I change the ArrayList to String
any function used from other subclasses won't work because they all T
.无法编译,因为它不接受
T
并且如果我将 ArrayList 更改为String
,其他子类中使用的任何 function 都将不起作用,因为它们都是T
。 Any help would be greatly appreciated.任何帮助将不胜感激。
thanks in advance.提前致谢。
EDIT: Since you want to partition your orders and not sort, you can use something like this:编辑:由于您想对订单进行分区而不是排序,因此可以使用以下内容:
dataCollection.stream().collect(
Collectors.groupingBy(order -> order.getIdentifier())
)
Here, this groups them by their identifiers and puts them into a Map
.在这里,这将它们按标识符分组并将它们放入
Map
中。 The order.getIdentifier()
part is just a placeholder for whatever you want to use to divide them up. order.getIdentifier()
部分只是您想要用来划分它们的任何内容的占位符。 The return type will be Map<TypeOfIdentifier, T>
.返回类型将为
Map<TypeOfIdentifier, T>
。
For this to work, though, your T
has to be of some specific type ( T extends Product
perhaps?) so you can get the identifier.但是,要使其正常工作,您的
T
必须是某种特定类型( T extends Product
?),以便您可以获得标识符。 Since I don't know the code for differentiating between different products, I can't put the exact code here.由于我不知道区分不同产品的代码,所以我不能在这里放确切的代码。
The Javadoc for Collectors
Collectors
的 Javadoc
This is why Collections.sort wasn't working for you, but you don't need Collections.sort anyways.这就是为什么 Collections.sort 不适合你,但你不需要 Collections.sort 反正。
T must extend the Comparable interface, because obviously you can't sort objects of just any type. T 必须扩展Comparable接口,因为显然您不能对任何类型的对象进行排序。 The Comparable interface has a
compareTo
method that lets you sort. Comparable 接口有一个
compareTo
方法,可让您进行排序。
An alternative would be to write a custom Comparator
that defines a single method: compare
, which would take 2 objects of type T
and return an int
representing the order (in most cases it's basically the first argument minus the second argument).另一种方法是编写一个自定义的
Comparator
,它定义了一个方法: compare
,它将接受 2 个T
类型的对象并返回一个表示顺序的int
(在大多数情况下,它基本上是第一个参数减去第二个参数)。 For this, you would need to use Collections.sort(dataCollection, customComparator)
.为此,您需要使用
Collections.sort(dataCollection, customComparator)
。
You can define your comparator with a lambda expression, but I can't help you beyond that because I have no idea how you want to sort your objects.您可以使用 lambda 表达式定义比较器,但除此之外我无法帮助您,因为我不知道您想如何对对象进行排序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.