2016-04-26 80 views
2

我有兩個對象列表。 PersonPurchaseOrderJava 8:通過編號合併兩個對象列表

Person有姓名,年齡,身份證等
PurchaseOrder有PERSONID(FK人ID),時間戳,金額等

使用Java 8,我如何才能購買的平均人的年齡的訂單金額< 18?

List<Person> personList = Arrays.asList(person); 
List<PurchaseOrder> purchaseOrderList = Arrays.asList(purchaseOrders); 

List<Person> underAgePerson = personList.stream() 
     .filter(p -> p.getAge < 18) 
     .collect(Collectors.toList()); 

// TODO: 
purchaseOrderList.stream() 
     .forEach(o1 -> underAgePerson.stream() 
       .filter(o2 -> o1.getPersonId() == o2.getId())); 

purchaseOrderList.stream().mapToDouble(o2 -> Long.valueOf(o2.getAmount())).average(); 
+0

我看你找到了答案,但我只是好奇的東西。你在計算平均值是什麼?金額數量的總和肯定是平均值,但每個金額的平均值是多少?你不想要像每個人的平均金額? –

+0

我剛剛嘗試了Java 8,並且被困在如何合併兩個列表中。 – sophie

回答

2

我將創建一組人物ID誰是< 18然後計算他們的購買平均:

List<Person> persons = Arrays.asList(
    new Person(1, 18), //(id, age) 
    new Person(2, 24), 
    new Person(3, 14), 
    new Person(4, 10) 
); 

//Same person can place multiple purchases. 
List<PurchaseOrder> purchaseOrders = Arrays.asList(
    new PurchaseOrder(1, 24), //(person id, purchase amount) 
    new PurchaseOrder(1, 40), 
    new PurchaseOrder(2, 10), 
    new PurchaseOrder(2, 24), 
    new PurchaseOrder(3, 23), 
    new PurchaseOrder(3, 45), 
    new PurchaseOrder(4, 68), 
    new PurchaseOrder(4, 12), 
    new PurchaseOrder(4, 23) 
); 

Set<Integer> personIds = persons 
    .stream() 
    .filter(person -> person.getAge() < 18) 
    .map(Person::getId) 
    .collect(Collectors.toSet()); 

OptionalDouble average = purchaseOrders 
    .stream() 
    .filter(purchaseOrder -> personIds.contains(purchaseOrder.getPersonId())) 
    .mapToInt(PurchaseOrder::getAmount) 
    .average(); 
0

我會先取18以上的集合。

Set<String> over18 = personList.stream() 
           .filter(p -> p.getAge < 18) 
           .map(Person::getId) 
           .collect(Collectors.toSet()); 
List<PurchaseOrder> over18orders = purchaseOrderList.stream() 
              .filter(o -> over18.contains(o.getId()) 
              .collect(Collectors.toList()); 
double sum = over18Orders.stream().mapToDouble(o -> o.getValue()).sum(); 
double average = sum/over18.size(); // average per person. 
+1

'toSet'和'toList'確實存在嗎?或者是'collect(Collectors.toList())'的簡寫? –

+1

它應該是'18歲以下'而不是結束。並懷疑,超過18集包含一套人而不是身份證,「over18.contains(o.getId())'工作如何? –

+0

@DanielKaplan'toArray'就是我想到的。 + 1 –