繁体   English   中英

Java 8 - 如何从List中获取对象的多个属性?

[英]Java 8 - how to get multiple attributes of an object from a List?

我有一个由Google Places API返回的地点列表,并决定找到价格最低的地方。

以下是我使用Java 8实现它的方法:

BigDecimal lowestPrice = places.stream()
                .collect(Collectors.groupingBy(Place::getPrice, Collectors.counting()))
                .entrySet().stream().min(Map.Entry.comparingByValue())
                .map(Map.Entry::getKey)
                .orElse(BigDecimal.ZERO); 

它返回了我的最低价格,但获得Place的名称也很棒(它有一个name属性)。

我怎样才能返回价格最低的地方name

为什么不返回整个Place对象?

places.stream().min(Comparator.comparing(Place::getPrice)).get()

首先,你似乎真的不清楚你最初想要什么,你好像这么说

我有一个由Google Places API返回的地点列表,并决定找到价格最低的地方

然后在你的描述的底部,你说:

它返回了我的最低价格,但获得Place的名称也很棒 (它有一个名称属性)。

好像后者似乎是你想要的?

不过,这里有两个解决方案:

如果你想在分组之后按照计数找到最小值,无论出于什么原因......那么你可以做以下事情:

 places.stream()
       .collect(Collectors.groupingBy(Place::getPrice))
       .entrySet().stream()
       .min(Comparator.comparingInt((Map.Entry<Integer, List<Place>> e) -> e.getValue().size()))
       .map(e -> new SimpleEntry<>(e.getKey(), e.get(0)));  

请注意,上面我使用了Integer作为输入键,如果它不是Integer ,请随意将其更改为相应的类型。


否则,如果您只是在价格最低的对象之后,那么您可以:

places.stream().min(Comparator.comparingInt(Place::getPrice));

要么:

Collections.min(places, Comparator.comparingInt(Place::getPrice));

不需要分组和所有的事情。

你应该找Place用最低的价格,而不是最低的价格和Place是建议吧:

places.stream()
      .min(Comparators.comparing(Place::getPrice)) // compare by Price. Should use a second criteria for Place with same Price
      ; // return Optional<Place>

如果你真的需要计算,你仍然可以这样做:

  BigDecimal lowestPrice = places.stream()
            .collect(Collectors.groupingBy(Place::getPrice, toList()))
            .entrySet()
            .stream()
            .min(Map.Entry.comparingByKey()) // Optional<Map.Entry<BigDecimal, List<Place>>
            .map(Map.Entry::getValue)
            // places = List<Place>, you can use size()
            .ifPresent(places -> places.forEach(System.out::println));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM