我正在尝试改进基于框中Storage
信息选择Summary
框的给定算法。为了检索具有最高numItems属性(摘要对象)的标识符(摘要对象),我将不得不排序Summary[]
,一个对象数组,但我无法想象如何按属性排序。
我找到了许多创建ArrayList<Int> a = new ArrayList<Int>();
然后使用Collections
获取最大价值的示例,但在这里,我对其他属性感兴趣,而我无法想象我将如何做到这一点。你能帮我吗?
public String selectNextDelivery(StorageBox.Summary[] summaries) throws NoBoxReadyException {
if (summaries.length != 0) {
for(StorageBox.Summary summary : summaries){
if (summary.numItems > 0) {
return summary.identifier;
}
}
}
// Otherwise no box is ready
throw new NoBoxReadyException();
}
答案 0 :(得分:3)
在Java 8中,要使用属性获取对象数组中的最大元素,请将Stream#max()
与Comparator.comparingInt()
一起使用
return Stream.of(summaries)
.max(Comparator.comparingInt(s -> s.numItems))
.orElseThrow(() -> new NoBoxReadyException())
.identifier;
如果没有Java 8,您可以将Collections.max()
与自定义Comparator
:
try {
return Collections.max(Arrays.asList(summaries), new Comparator<StorageBox.Summary>() {
@Override
public int compare(StorageBox.Summary s1, StorageBox.Summary s2) {
return Integer.compare(s1.numItems, s2.numItems);
}
}).identifier;
} catch (NoSuchElementException nsee) {
throw new NoBoxReadyException();
}
或者您可以使用标准的for
循环自行实现它:
if (summaries.length == 0)
throw new NoBoxReadyException();
StorageBox.Summary max = summaries[0];
for (int i = 1; i < summaries.length; i++)
if (summaries[i].numItems > max.numItems)
max = summaries[i];
return max.identifier;
答案 1 :(得分:1)
如果您熟悉Java 8 Streams,您可以执行以下操作:
Stream.of(summaries) //creating custom comparator which sorts based on identifier
.sort(($1, $2) -> Integer.compare($1.identifier, $2.identifier))
//Do something with your stream
如果你想从流中获取第一个元素,你可以这样做:
Stream.of(summaries)
.max(Comparator.comparingInt(StorageBox.Summary::getIdentifier))
.orElse(null);
感谢4castle指出Comparator.comparingInt()方法
答案 2 :(得分:0)
也许您想要的是使用S[:, None]
api,它具有用于确定最大元素的比较器。空值表示应该使用元素的自然顺序。
答案 3 :(得分:0)
您可以使用比较器进行排序 -
Arrays.sort(summaries, new Comparator<Summary>() {
@Override
public int compare(Summary o1, Summary o2) {
return o1.numItems.compareTo(o2.numItems);
}
});
或使用Collections api和Comparator来检索最大值
Summary maxSummary = Collections.max(Arrays.asList(summaries),
new Comparator<Summary>() {
@Override
public int compare(Summary o1, Summary o2) {
return o1.numItems.compareTo(o2.numItems);
}
});