在流中添加lambda以定义列表是否反转

我有以下方法:

    private List<Residence> getHighestPriceResidenceDistinct(List<Residence> residences, Sort.Direction direction, int numOfResidences) {
        return residences.stream()
            .collect(
                    Collectors.groupingBy(
                            SlotWinTransaction::getResidenceId,
                            Collectors.maxBy(Comparator.comparing(Residence::getPrice))
                    )
            )
            .values()
            .stream()
            .filter(Optional::isPresent)
            .map(Optional::get)
            .sorted(Comparator.comparing(Residence::getPrice).reversed())
            .limit(numOfResidences)
            .collect(Collectors.toList());
    }

It returns n number of Residence objects - in a list. A Residence object has fields price::BigDecimal, and id::String. The above method, requests the numOfResidences unique, most expensive Residence objects, and -due to the addition of reversed() - lists them starting from the most expensive one. The getHighestPriceResidenceDistinct method also has the Sort.Direction parameter. I would like to add a lambda expression, that defines if the reversed() will be used based on the value of the direction parameter.

评论
  • 我是歌手
    我是歌手 回复

    这是你想要的?

        private List<Residence> getHighestPriceResidenceDistinct(List<Residence> residences, Sort.Direction direction, int numOfResidences) {
        return residences.stream()
            .collect(
                    Collectors.groupingBy(
                            SlotWinTransaction::getResidenceId,
                            Collectors.maxBy(Comparator.comparing(Residence::getPrice))
                    )
            )
            .values()
            .stream()
            .filter(Optional::isPresent)
            .map(Optional::get)
            .sorted(Sort.Direction == "asc"? Comparator.comparing(Residence::getPrice): Comparator.comparing(Residence::getPrice).reversed())
            .limit(numOfResidences)
            .collect(Collectors.toList());
    }