具有最大值的对象列表

ᴘᴀɴ*_*ᴛɪs 2 java max

考虑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
Run Code Online (Sandbox Code Playgroud)

我想过滤掉包含具有最大值的项目的列表.在那种情况下,因为最大数量是9,我将收到{Item[3],Item[5],Item[9]}.我这样做的方法是首先迭代整个列表,然后在某处存储最大值(9)然后再次迭代它并将其字段等于9的项添加到新列表中.

但是每次我想要做类似的事情时,这都是很多代码,并且看起来效率不高.有没有更好的方法(无论是效率还是整洁)?

Tho*_*mas 5

我可能会一次性选择这些物品.

像这样的伪代码:

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 );
  }
}
Run Code Online (Sandbox Code Playgroud)