使用流从列表中获取最高的值,不同的元素

问题描述 投票:0回答:2

我有一个ArrayListBottle个对象。每个Bottle对象都有一个brand:String和一个price:double字段。我正在尝试修改下面的表达式-也许通过添加一个lambda-所以不仅我最终得到了一个独特瓶的列表,而且还获得了价格最高的独特瓶的列表-例如如果ArrayList包含三个同名的Bottle对象,那么我希望将价格最高的一个对象放入最终列表。

bottles.stream()
.filter(bottle -> processedGameRef.equalsIgnoreCase(bottle.getName()))
.findFirst().orElse(null);
java-8 functional-programming java-stream
2个回答
0
投票

您可以创建地图,以品牌名称为键,以瓶子为值。然后使用合并功能,如果找到另一个具有相同名称的瓶子,它将使瓶子保持最高价格。然后在最后收集地图值。在实践中看起来很热。

Collection<Bottle> highestPriceBottles = bottles.stream()
    .collect(Collectors.toMap(Bottle::getBrand, b -> b,
        BinaryOperator.maxBy(Comparator.comparingDouble(Bottle::getPrice))))
    .values();

0
投票

这里是如何以最高价格找到独特商品的示例

import org.junit.jupiter.api.Test;

import java.util.List;
import java.util.stream.Collectors;

public class ArrayTest {

    public static class Bottle {
        private final String name;
        private final double price;

        public Bottle(final String name, final double price) {
            this.name = name;
            this.price = price;
        }

        public String getName() {
            return name;
        }

        public double getPrice() {
            return price;
        }

        @Override
        public String toString() {
            return "Bottle{" +
                "name='" + name + '\'' +
                ", price=" + price +
                '}';
        }
    }

    @Test
    public void uniqueBottles() {
        List<Bottle> bottles = List.of(
            new Bottle("bottle1", 1.),
            new Bottle("bottle1", 2.),
            new Bottle("bottle1", 3.),
            new Bottle("bottle2", 3.5),
            new Bottle("bottle2", 1.5)
        );

        var processedBottleList = bottles
            .stream()
            .collect(Collectors.toMap(Bottle::getName, Bottle::getPrice, (p, p2) -> p > p2 ? p : p2))
            .entrySet()
            .stream()
            .map(e -> new Bottle(e.getKey(), e.getValue()))
            .collect(Collectors.toList());

        System.out.println(processedBottleList);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.