【问题标题】:Java Filters Finding the most expensive house in each CityJava过滤器查找每个城市最昂贵的房子
【发布时间】:2020-06-06 21:21:59
【问题描述】:

我有许多城市的房屋清单。我正在尝试使用过滤器来生成每个城市最昂贵的房子的列表。我无法使用常规循环。

//This returns unique City Names
List unique = obList.stream()
    .map(x -> x.getCity())
    .distinct()
    .sorted()
    .collect(Collectors.toList());

//This returns the house with the highest price in that city
RAddress obReturn = obList.stream()
        .filter(x -> x.getCity().equalsIgnoreCase(sName))
        .sorted((x,y) -> (int)(y.getPrice() - x.getPrice()))
        .findFirst()
        .get();

我知道以某种方式结合这些对于这个问题是必要的,但我一生都无法弄清楚如何......

感谢任何和所有的帮助。

【问题讨论】:

    标签: java lambda filter java-stream


    【解决方案1】:

    使用groupingBy收集器将每个城市的所有房屋一起收集;然后使用下游的maxBy 收集器只保留每个城市最昂贵的房子:

    obList.stream()
        .collect(
            groupingBy(
                x -> x.getCity(),
                maxBy(comparing(x -> x.getPrice())))
    

    这会返回一个Map<CityType, Optional<HouseType>>(其中CityTypeHouseType 分别是城市和房屋的类型。

    如果你想要一个Map<CityType, HouseType>(也就是说,没有Optional,因为你知道这个值总是存在的),包装下游收集器:

    collectingAndThen(maxBy(...), Optional::get)
    

    【讨论】:

    • “MaxBy”似乎不是关键字,我一定是做错了什么。
    • maxBy is a method in the Collectors classgroupingBy 也是如此。
    • @user11376058 为了明确起见,上面的代码依赖于来自Collectors 类的static import,如果您的城市属于String 类型且价格为@987654340,则返回类型为Map<String, Optional<Integer>> @.
    • 或使用toMap(x -> x.getCity(), Function.identity(), maxBy(comparing(x -> x.getPrice()))),现在使用BinaryOperator.maxBy(…)。那么你就不需要处理Optional了。另见this Q&A...
    猜你喜欢
    • 2011-08-04
    • 1970-01-01
    • 2015-04-24
    • 2022-01-22
    • 2017-12-23
    • 1970-01-01
    • 2010-09-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多