考虑一个 Item 的对象列表,其中每个项目都与一个整数字段相关联:
Item[0]->1
Item[1]->4
Item[2]->2
Item[3]->9
Item[4]->1
Item[5]->9
Item[6]->3
Item[7]->6
Item[8]->7
Item[9]->9
我想过滤掉具有最大值的项目的列表。在这种情况下,由于最大数量为 9,我将收到 {Item[3],Item[5],Item[9]}
。我这样做的方法是必须首先迭代整个列表,然后将最大值 (9) 存储在某处,然后再次迭代并将其字段等于 9 的项目添加到新列表中。
但是每次我想做类似的事情时都会有很多代码,而且看起来效率不高。是否有更好的方法(无论是在效率还是整洁方面)?
最佳答案
我可能会一次性选择这些项目。
像这样的伪代码:
int max = Integer.MIN_VALUE;
Set<Item> maxItems = new LinkedHashSet<>();
for( Item item : items ) {
//if the item has a greater value clear the set and set the new max value
if( item.value > max ) {
maxItems.clear();
max = item.value;
}
//due to the code above value should always be <= max here, so we just need to check ==
if( item.value == max ) {
maxItems.add( item );
}
}
关于java - 具有最大值的对象列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27569735/