猿问

Java Strems - 提取嵌套对象和组

我正在处理以下 POJO:


@Getter

@AllArgsConstructor

public class Order {


  private int quantity;

  private Category category;

  private LocalDate date;

  //rest fields


}

我有一个这个对象的列表,我想要做的是我想找到月份(从date字段中提取)和类别(它是枚举类型),它具有最高的quantity. 我想用流来做,我做了很少的尝试,但现在我没有想法。你能帮我解决这个问题吗?


在我试图解决这种情况的虚拟尝试下面:


   Optional<Entry<Month, Order>> result = orders.stream()

        .collect(

            Collectors.groupingBy(Order::getLocalDate, Collectors.maxBy(Comparator.comparingInt(Order::getQuantity))))

        .entrySet()

        .stream()

        .collect(Collectors.toMap(e -> e.getKey().getMonth(), e -> e.getValue().get()))

        .entrySet()

        .stream()

        .max(Entry.comparingByValue(Comparator.comparingInt(Order::getQuantity)));

例如,我们有以下数据列表:


List<Order> orders = Arrays.asList(

    new Order(Category.HEADPHONES,3, LocalDate.of(2018, 2, 22)),

    new Order(Category.HEADPHONES,6, LocalDate.of(2018, 2, 23)),

    new Order(Category.NOTEBOOKS,8, LocalDate.of(2018, 2, 24)),

    new Order(Category.NOTEBOOKS,4, LocalDate.of(2018, 3, 3)),

    new Order(Category.NOTEBOOKS,1, LocalDate.of(2018, 3, 3)),

    new Order(Category.PHONES,2, LocalDate.of(2018, 3,5)),

    new Order(Category.PHONES,2, LocalDate.of(2018, 3,7))

);

我想玩流并接收结果(例如一些包含month, category,的元组quantity)。


在上述数据集中,数量值最高的月份 ( 9) 属于February类别HEADPHONES。


梵蒂冈之花
浏览 136回答 2
2回答

蝴蝶刀刀

您可以按SimpleEntry两个字段的一对(在此示例中使用)进行分组,计算每个组的数量总和,然后对结果进行流式处理以选择具有最高值的条目:orders.stream()&nbsp; &nbsp; .collect(Collectors.groupingBy(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; o -> new SimpleEntry<>(o.getDate().getMonth(), o.getCategory()),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Collectors.summingInt(Order::getQuantity)))&nbsp; &nbsp; .entrySet()&nbsp; &nbsp; .stream()&nbsp; &nbsp; .max(Entry.comparingByValue())&nbsp; &nbsp; .ifPresent(cat -> System.out.println(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "Month: " + cat.getKey().getKey() +&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; " - Category: " + cat.getKey().getValue() +&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; " - Quantity: " + cat.getValue()));使用您的示例数据的输出是:Month: FEBRUARY - Category: HEADPHONES - Quantity: 9

陪伴而非守候

这是一个如何仅针对月份执行此操作的示例(可以引入另一个类来组合键以进行聚合):// month, sumMap<Integer, Integer> map = orders.stream()&nbsp; &nbsp; &nbsp; &nbsp; .collect(groupingBy(o -> o.getDate().getMonthValue(), TreeMap::new, summingInt(Order::getQuantity)));int month = map.entrySet().stream().reduce((s1, s2) -> {&nbsp; &nbsp; if (s1.getValue() > s2.getValue()) return s1;&nbsp; &nbsp; else return s2;}).get().getKey();为清楚起见,我将其分为两个流,但您可以加入它们。第一个给出订单总和的月份数,第二个是最大的月份值。
随时随地看视频慕课网APP

相关分类

Java
我要回答