当从List派生密钥时,如何迭代番石榴MultiMap

时间:2015-10-09 14:30:40

标签: java guava

我有订单日期和订单价值的订单清单。如何按订单日期分组并计算每个订单日期的订单总值。我怎样才能在Google Guava中实现这一目标?如果它的复杂性......我如何在Java集合中实现这一点?

订购POJO

Date date;
Integer Value;

Util.java

    ListMultimap<Date, Integer> listMultiMap = ArrayListMultimap.create();
    for(Order o : orders){
      listMultiMap.put(o.date, o.value);
   }
   //Now how do I iterate this listMultiMap and calculate the total value?

1 个答案:

答案 0 :(得分:1)

我认为Guava不一定是这里最好的工具......也不是任何普通的地图,就此而言:如果你有大量的订单,你应该考虑使用Java8 Streams,它会让你并行化你的计算。它还将对原始类型(int与Integer)进行优化...

在任何情况下,对于您描述并遵循您发布的起始代码的特定用例,这里是一个潜在的解决方案(使用LocalDate而不是Date只是因为它更方便):

@Test
public void test(){

    // Basic test data
    Order today1 = new Order(LocalDate.now(),1);
    Order today2 = new Order(LocalDate.now(),2);
    Order today3 = new Order(LocalDate.now(),5);
    Order tomorrow1 = new Order(LocalDate.now().plusDays(1),2);
    Order yesterday1 = new Order(LocalDate.now().minusDays(1),5);
    Order yesterday2 = new Order(LocalDate.now().minusDays(1),4);
    List<Order> list = Lists.newArrayList(today1,today2,today3,tomorrow1,yesterday1,yesterday2);

    // Setup multimap and fill it with Orders
    ListMultimap<LocalDate, Integer> mm = ArrayListMultimap.create();
    for(Order o : list){
        mm.put(o.date,o.value);
    }

    // At this point, all you need to do is, for each date "bucket", sum up all values.
    Map<LocalDate, Integer> resultMap = Maps.newHashMap();
    for(LocalDate d : mm.keySet()){
        List<Integer> values = mm.get(d);
        int valuesSum = 0;
        for(int i : values){
            valuesSum += i;
        }
        resultMap.put(d,valuesSum);
    }

    /*
    * Result map should contain:
    * today -> 8
    * tomorrow -> 2
    * yesterday -> 9
    * */
    assertThat(resultMap.size(), is(3));
    assertThat(resultMap.get(LocalDate.now()), is(8));
    assertThat(resultMap.get(LocalDate.now().minusDays(1)), is(9));
    assertThat(resultMap.get(LocalDate.now().plusDays(1)), is(2));
}