Spasitel
Spasitel

Reputation: 169

Java Stream grouping and counting occuerences

I have a list of objects representing trades in a market. Each trade has an opening and closing time and a profit. I want to group them by a month and then count a number of trades with profit > 0 and < 0 in each month = create a Map with following structure {"MM" = {"Win" = numberOfWinTrades, "Loss" = numberOfLossTrades}, "MM" ...}

I came up with the following code, but I am not able to implement the condition into it:

filteredOrders.stream().collect(Collectors.groupingBy(order -> order.getCreationTime().substring(5,7),
                Collectors.groupingBy(order -> order.getPlUsd() > 0, Collectors.counting())));

Upvotes: 1

Views: 59

Answers (1)

ernest_k
ernest_k

Reputation: 45319

You can use an inline mapping based on the order.getPlUsd() > 0/order.getPlUsd() < 0 condition:

Map<String, Map<String, Long>> monthPlusdGroups = 
    filteredOrders.stream()
    .collect(Collectors.groupingBy(order -> order.getCreationTime().substring(5, 7),
             Collectors.groupingBy(order -> order.getPlusd() > 0 ? "Win" : "Loss", 
                                   Collectors.counting())));

Just note that this implementation (order.getPlusd() > 0 ? "Win" : "Loss") classifies $0 profits as "Loss".

Upvotes: 3

Related Questions