我正在尝试改进基于盒子上的Summary
信息选择Storage
盒子的给定算法。为了检索(摘要对象的)具有最高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();
}
发布于 2016-08-22 13:13:15
在Java8中,要使用属性获取对象数组中的最大元素,可以使用带有Comparator.comparingInt()
的Stream#max()
return Stream.of(summaries)
.max(Comparator.comparingInt(s -> s.numItems))
.orElseThrow(() -> new NoBoxReadyException())
.identifier;
在没有Java8的情况下,您可以使用带有自定义Comparator
的Collections.max()
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;
发布于 2016-08-22 13:02:15
如果您熟悉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中获取按某个属性排序的第一个元素,您可以这样做:
Stream.of(summaries)
.max(Comparator.comparingInt(StorageBox.Summary::getIdentifier))
.orElse(null);
感谢4castle指出了一个Comparator.comparingInt()方法
发布于 2016-08-22 13:03:55
也许您想要的是使用public static <T> T max(Collection<? extends T> coll, Comparator<? super T> comp)
应用程序接口,它具有用于确定最大元素的比较器。空值表示应使用元素的自然排序。
https://stackoverflow.com/questions/39071645
复制相似问题