Java 8将对象分组为集合

3
我想在到期日期上对租赁对象的集合进行分组,但我希望为每个组创建一个新的RentalReport对象,其中键是预定义值(枚举),而该组是该对象的属性。 通过在每个条件上过滤集合并为每个条件创建一个RentalReport对象,我已经实现了这一点,但我想知道是否可以使用Collectors类的groupingBy方法来完成此操作。
在Java 8中,是否可以按预定义的筛选集进行分组,以便我可以创建一个映射,其中键是枚举,值是租赁对象的集合。 然后我可以遍历此映射并生成RentalReport对象。
我已经创建了此演示,但实际任务涉及多个group by子句,因此如果可以通过分组实现这一点,那将非常好。
    import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import org.joda.time.DateTime;

public class TestGrouping {

    enum RentalClassification {
        UNRESTRICTED, //No restriction restricted=false
        OVERDUE,      //todays date after due date.
        NEARLY_OVERDUE, // todays date after due date + 2 days
        NOT_OVERDUE
    }

    public static void main(String[] args) {

        class Rental {
            Integer rentalId;
            Integer productId;
            boolean restricted;
            DateTime dueDate;

            public Rental(Integer rentalId, Integer productId, boolean restricted, DateTime dueDate){
                this.rentalId = rentalId;
                this.productId = productId;
                this.restricted = restricted;
                this.dueDate = dueDate;
            }

            public Integer getRentalId() {
                return rentalId;
            }

            public void setRentalId(Integer rentalId) {
                this.rentalId = rentalId;
            }

            public Integer getProductId() {
                return productId;
            }

            public void setProductId(Integer productId) {
                this.productId = productId;
            }

            public boolean isRestricted() {
                return restricted;
            }

            public void setRestricted(boolean restricted) {
                this.restricted = restricted;
            }

            public DateTime getDueDate() {
                return dueDate;
            }

            public void setDueDate(DateTime dueDate) {
                this.dueDate = dueDate;
            }

            public String toString(){
                return "RentalId:"+this.rentalId+". ProductId:"+this.productId+". Due date:"+this.dueDate+". -";
            }
        }

        class RentalReport {

            RentalClassification classification;
            List<Rental> rentals;

            public RentalReport(RentalClassification classification, List<Rental> rentals) {
                this.classification = classification;
                this.rentals = rentals;
            }

            public RentalClassification getClassification() {
                return classification;
            }
            public void setClassification(RentalClassification classification) {
                this.classification = classification;
            }
            public List<Rental> getRentals() {
                return rentals;
            }
            public void setRentals(List<Rental> rentals) {
                this.rentals = rentals;
            }

            public String toString(){
                StringBuilder sb = new StringBuilder("Classification:"+this.classification.name()+". Rental Ids:");
                this.rentals.forEach(r -> sb.append(r.getRentalId()));
                return sb.toString();

            }

        }

        DateTime today = new DateTime();

        List<Rental> rentals = Arrays.asList(
                new Rental(1,100, true, today.plusDays(-10)),
                new Rental(2,101, false, today.plusDays(-10)),
                new Rental(3,102, true, today.plusDays(-4)),
                new Rental(4,103, true, today.plusDays(-4)),
                new Rental(5,104, true, today.plusDays(-4)),
                new Rental(6,105, true, today.plusDays(2)),
                new Rental(7,106, true, today.plusDays(2)),
                new Rental(8,107, true, today.plusDays(2)),
                new Rental(9,108, true, today.plusDays(4)),
                new Rental(10,109, true, today.plusDays(5))
                );


        List<RentalReport> rentalReports = new ArrayList<RentalReport>();

        List<Rental> unrestrictedRentals = rentals.stream()
                                           .filter(r -> !r.isRestricted())
                                           .collect(Collectors.toList());

        rentalReports.add(new RentalReport(RentalClassification.UNRESTRICTED, unrestrictedRentals));

        List<Rental> overdueRentals = rentals.stream()
                                      .filter(r -> r.isRestricted() && r.getDueDate().isBefore(new DateTime()))
                                      .collect(Collectors.toList());

        rentalReports.add(new RentalReport(RentalClassification.OVERDUE, overdueRentals));

        List<Rental> nearlyOverdueRentals = rentals.stream()
                                            .filter(r -> r.isRestricted() 
                                                    && r.getDueDate().isAfter(new DateTime())
                                                    && r.getDueDate().isBefore(new DateTime().plusDays(2)))
                                            .collect(Collectors.toList());

        rentalReports.add(new RentalReport(RentalClassification.NEARLY_OVERDUE, nearlyOverdueRentals));

        List<Rental> notOverdueRentals = rentals.stream()
                                        .filter(r -> r.isRestricted() && r.getDueDate().isAfter(new DateTime()))
                                        .collect(Collectors.toList());

        rentalReports.add(new RentalReport(RentalClassification.NOT_OVERDUE, notOverdueRentals));

        System.out.println("Rental Reports: "+rentalReports.toString());

    }
    }
4个回答

2
你的4个枚举常量和4个测试 Lambda 表达式之间显然存在一对一的关系。因此,将每个Lambda表达式集成到相应的枚举常量中是有意义的。
每个枚举常量都将其测试 Lambda 表达式保存为Predicate<Rental>。 枚举类型将具有一个boolean test(Rental) 方法,使用自己的Predicate进行测试。
顺便说一句:由于那个 test 方法,我们可以将 implements Predicate<Rental> 添加到枚举类型中。这在最后会非常有用。
enum RentalClassification implements Predicate<Rental> {

    UNRESTRICTED(    //No restriction restricted=false
            r -> !r.isRestricted()),
    OVERDUE(         //todays date after due date.
            r -> r.isRestricted()
            && r.getDueDate().isBefore(new DateTime())),
    NEARLY_OVERDUE( // todays date after due date + 2 days
            r -> r.isRestricted() 
            && r.getDueDate().isAfter(new DateTime())
            && r.getDueDate().isBefore(new DateTime().plusDays(2))),
    NOT_OVERDUE(
            r -> r.isRestricted()
            && r.getDueDate().isAfter(new DateTime()));

    private RentalClassification(Predicate<Rental> predicate) {
        this.predicate = predicate;
    }

    private Predicate<Rental> predicate;

    @Override
    public boolean test(Rental r) {
       return predicate.test(r);
    }
}

使用这个增强的enum类型,您可以编写一个简单的方法来对Rental进行分类。 它将循环遍历所有的RentalClassification常量,直到找到一个测试成功的为止:
static RentalClassification classify(Rental rental) {
   for (RentalClassification classification : RentalClassification.values()) {
       if (classification.test(rental))
           return classification;
   }
   return null;  // should not happen
}

使用这种分类方法,您可以轻松创建所需的地图:
Map<RentalClassification, List<Rental>> map =
        rentals.stream()
               .collect(Collectors.groupingBy(r -> classify(r)));

或者,还存在一个稍微不同的方法。它直接使用enum常量作为过滤器谓词来获取多个列表:

List<Rental> unrestrictedRentals =
        rentals.stream()
               .filter(RentalClassification.UNRESTRICTED)
               .collect(Collectors.toList());
List<Rental> overdueRentals =
        rentals.stream()
               .filter(RentalClassification.OVERDUE)
               .collect(Collectors.toList());
// ...

这很不错,谢谢。这就是我将要在我的项目中实现的方式。 :) - jonesy

1
如何像这样做一些事情:
rentals.stream().collect(Collectors.groupingBy(r -> {
    if (!r.isRestricted()) {
        return RentalClassification.UNRESTRICTED;
    }
    if (r.isRestricted() && r.getDueDate().isBefore(new DateTime())) {
        return RentalClassification.OVERDUE;
    }
    // and so on
}));

也许值得将lambda添加到Rental作为一个方法 RentalClassification getRentalClassification()


1
这里是一种方法:
List<RentalClassification,List<Rental>> = rentals
                                            .stream()
                                            .map(r -> getClassifiedRental(r))
                                            .collect(Collectors.groupingBy(SimpleEntry::getKey,Collectors.mapping(SimpleEntry::getValue,Collectors.toList())))

整个技巧在于 getClassifiedRental(Rental r) 方法中:
SimpleEntry<RentalClassification,Rental> getClassifiedRental(Rental r){

    if(r -> !r.isRestricted())
        return new SimpleEntry<RentalClassification,Rental>(RentalClassification.UNRESTRICTED,r);

    if(r -> r.isRestricted() && r.getDueDate().isBefore(new DateTime()))

        return new SimpleEntry<RentalClassification,Rental>(RentalClassification.OVERDUE,r);

    if(r -> r.isRestricted() 
            && r.getDueDate().isAfter(new DateTime())
            && r.getDueDate().isBefore(new DateTime().plusDays(2)))
        return new SimpleEntry<RentalClassification,Rental>(RentalClassification.NEARLY_OVERDUE,r);

    if(r -> r.isRestricted() && r.getDueDate().isAfter(new DateTime()))
        return new SimpleEntry<RentalClassification,Rental>(RentalClassification.NOT_OVERDUE,r);

}

SimpleEntryMap.Entry接口的自定义实现(您需要自己编写):

public class SimpleEntry implements Entry<RentalClassification, Rental> {
// implementation
}

拥有getClassifiedRental(Rental r)可以帮助您更好地分离租赁分类程序,例如测试和重构等。

1
这是一种使用 groupingBy 方法的方法。
Function<Rental, RentalClassification> classifyRental = r -> {
    if (!r.isRestricted())
        return RentalClassification.UNRESTRICTED;
    else if (r.getDueDate().isBefore(new DateTime()))
        return RentalClassification.OVERDUE;
    else if (r.getDueDate().isAfter(new DateTime())
            && r.getDueDate().isBefore(new DateTime().plusDays(2)))
        return RentalClassification.NEARLY_OVERDUE;
    else
        return RentalClassification.NOT_OVERDUE;
};
Map<RentalClassification, List<Rental>> rentalReportMap = rentals.stream()
        .collect(groupingBy(classifyRental));
rentalReportMap
        .forEach((classification, rental) -> rentalReports.add(new RentalReport(classification, rental)));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接