列出流,获取最低价格的商品

时间:2016-10-18 16:14:10

标签: java java-stream

我有一个Hotel,每个BigDecimal minSellingPrice都有Hotel,我希望以最低售价获得hotels.stream().min((h1, h2) -> h1.getMinSellingPrice().compareTo(h2.getMinSellingPrice())).get()

我能够通过此代码

实现这一目标
minSellingPrice

但如果列表中的3家酒店有最低卖价,那么该列表有50家酒店,最低minSellingPrice为100,50家酒店中有3家酒店的map为100。

如何获得这3家酒店的清单,以便我可以对它们进行操作?我唯一想到的是通过minmain()获取最低价格然后查询列表中价格最低的商品,但这听起来不太好。

4 个答案:

答案 0 :(得分:3)

你可以在下面尝试获得最小酒店

Hotel min = hotels.stream().min(Comparator.comparing(Hotel::getSellingPrice)).orElse(null);

为了获得多家酒店,您需要使用groupingBy

Map<BigDecimal, List<Hotel>> groupedHoted = hotels.stream().collect(Collectors.groupingBy(Hotel::getSellingPrice, TreeMap::new, Collectors.toList()));

<强>更新

根据评论编辑

groupedHoted = new TreeMap<>(hotels.stream().collect(Collectors.groupingBy(Hotel::getSellingPrice)));

使用reduce(少推荐)

    Map<BigDecimal, List<Hotel>> sorted = hotels.stream().reduce(new TreeMap<BigDecimal, List<Hotel>>(), (map, hotel) -> {
        if (map.get(hotel.getSellingPrice()) == null) {
            map.put(hotel.getSellingPrice(), new ArrayList<>());
        }
        map.get(hotel.getSellingPrice()).add(hotel);
        return map;
    }, (map1, map2) -> {
        map1.putAll(map2);
        return map1;
    });

输出

{10=[Hotel [sellingPrice=10], Hotel [sellingPrice=10]], 20=[Hotel [sellingPrice=20], Hotel [sellingPrice=20]], 30=[Hotel [sellingPrice=30]]}

答案 1 :(得分:1)

如果您想对酒店列表进行排序:

Brush

这使用比较器documentation here

或者在列表中返回最低售价:

Comparator<Hotel> comp = new Comparator<Hotel>() {
            public int compare(Hotel o1, Hotel o2) {
                return o1.getMinSellingPrice() - o2.getMinSellingPrice();
            }
        };

hotels = hotels.stream().sorted(comp).collect(Collectors.toList());

这只是将酒店列表映射到他们的minSellingPrice列表,然后取最小值。

答案 2 :(得分:1)

使用Collectors.groupingBy()形式,您可以指定要使用的Map类型,并指定SortedMapNavigableMap实施。然后,您可以轻松地从结果中检索最小元素的集合。

NavigableMap<BigDecimal, List<Hotel>> hotelByPrice = hotels.stream()
    .collect(Collectors.groupingBy(Hotel::getMinSellingPrice, TreeMap::new, Collectors.toList()));
List<Hotel> cheapest = hotelByPrice.firstEntry().getValue();

答案 3 :(得分:0)

另一种可能性。

List<Hotel> minHotels = hotels.stream()
    .filter(h -> h.minSellingPrice == hotels.stream()
        .map(Hotel::getMinSellingPrice).sorted().findFirst().orElse(null))
    .collect(Collectors.toList());
相关问题