Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
85 views
in Technique[技术] by (71.8m points)

How to sum occurrence elements count in java 8

I want to find occurrence elements sum in java 8 and using my below technique i am getting all elements sum but i want to find only itemType=EQUIPMENT elements sum

Can some one help me please

double sum = itemList.stream().mapToDouble(a -> a.getQuantity())
                    .sum();

[
        {
            "itemType": "EQUIPMENT",
            "quantity": 6
        },
        {
            "itemType": "DTVN",
            "quantity": 2
        },
        {
            "itemType": "EQUIPMENT",
            "quantity": 1
        }
]
question from:https://stackoverflow.com/questions/65943035/how-to-sum-occurrence-elements-count-in-java-8

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can filter a particular itemType using equals or equalsIgnoreCase based on what you want

double sum = itemList.stream()
                .filter(type->"EQUIPMENT".equals(type.getItemType()))
                .mapToDouble(a -> a.getQuantity())
                .sum();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...