我有一份物品清单。
class Item {
private String name;
private int quantity;
}
列表包含类似
的项目List<Item> itemList = new ArrayList<>();
itemList.add(new Item("Item1", 5));
itemList.add(new Item("Item2", 10));
itemList.add(new Item("Item3", 10));
itemList.add(new Item("Item4", 7));
itemList.add(new Item("Item1", 15));
itemList.add(new Item("Item2", 16));
输出将是最大数量的项目列表,例如项目列表(“项目1”,15),项目(“项目2”,16),项目(“项目3”,10),项目(“项目4”,7) .
我尝试过,但没有得到确切的结果。
List<Item> maxQuantityItems = itemList.stream()
.filter(item -> item.getQuantity() == maxQuantity)
.collect(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Item::getName))));
您希望将物品收集到 Map 中,Map 会自动解决冲突并提供 lambda 函数来将值减少到您的要求中:此处为最高数量。代码应该如下所示:
var maxItems = itemList.stream()
.collect(Collectors.toMap(
Item::getName,
Function.identity(),
(item1, item2) -> item1.getQuantity() > item2.getQuantity() ? item1 : item2
)).values();
.values()
(从地图)提取所有最高数量项目的列表。