Michael
Michael

Reputation: 13614

How to summarize numeric property of stream of objects?

I try to summarize double property of stream of objects:

items.collect(Collectors.summingDouble(double::doubleValue)

But I get cannot resolve method 'doubleValue'

Here is item definition:

Stream items= ... ;

Here is Item object definition:

public class Item {
    private double price;
    private Date date;
    private String name;
}

How to calculate summarize property of stream of objects?

Upvotes: 2

Views: 586

Answers (4)

petrov.aleksandr
petrov.aleksandr

Reputation: 642

items.stream().collect(Collectors.summingDouble(Item::getPrice))

Upvotes: 7

abhinavsinghvirsen
abhinavsinghvirsen

Reputation: 2014

package com.feature;

import java.util.*;
import java.util.stream.Collectors;

public class Java8Feature {
    public static void main(String[] args) {
        
        Item o1=new Item(12.0d,"ab");
        Item o2=new Item(13.0d,"cd");
        Item o3=new Item(14.0d,"de");
        
        List al= new ArrayList<Item>();
        al.add(o1);
        al.add(o2);
        al.add(o3);
        

            Double  value =  (double)al.stream().collect(Collectors.summingDouble(Item::getPrice));
            System.out.println(value);//output  39.0
            
            

                         
        
    }
    
}


 class Item {
    private double price;
    private String name;
    
    public double getPrice() {
        return price;
    }
    public void setPrice(double price) {
        this.price = price;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    
    public Item(double price, String name) {
        
        this.price = price;
        
        this.name = name;
    }
    
    
}

Upvotes: 0

Panagiotis Bougioukos
Panagiotis Bougioukos

Reputation: 18919

Although other options are the optimals just for reference I post another alternative using streams, that was intended for such uses.

Double sum = items.stream().reduce(0D, (subtotal, element)-> subtotal + element.getPrice(), Double::sum);
       

Upvotes: 0

OLezhko
OLezhko

Reputation: 150

You can convert your object stream to a DoubleStream which has built-in sum method.

    items.stream().mapToDouble(Item::getPrice).sum();

Upvotes: 3

Related Questions