首页 文章

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

提问于
浏览
3

我有一个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

3 回答

  • 2

    您应该找到价格最低的 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));
    
  • 9

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

    我有一个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));
    

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

  • 4

    你为什么不归还整个 Place 对象?

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

相关问题