2

This question is partially answered here. My map will have trade Ids grouped by trade Type. This link gives me Trades grouped by tradeType. I know I can further manipulate it to get desired result, but just wondering if its possible in one go. Here is my code.

public static void main(String[] args) {
Trade trade1 = new Trade(1, TradeStatus.NEW, "type1",1);
Trade trade2 = new Trade(2, TradeStatus.FAILED, "type2",1);
Trade trade3 = new Trade(3, TradeStatus.NEW, "type1",1);
Trade trade4 = new Trade(4, TradeStatus.NEW, "type3",1);
Trade trade5 = new Trade(5, TradeStatus.CHANGED, "type2",1);
Trade trade6 = new Trade(6, TradeStatus.EXPIRED, "type1",2);

List<Trade> list = new ArrayList<>();
list.add(trade1);
list.add(trade2);
list.add(trade3);
list.add(trade4);
list.add(trade5);
list.add(trade6);


Map<String, List<Trade>> result =
         list.stream().collect(Collectors.groupingBy(Trade::getTradeType));

System.out.println(result);//prints Trades grouped by trade type


Map<String, List<String>> unvaluedtradesMap = new HashMap<>();
for (Trade trade : list) {
    String tradeType = trade.getTradeType();
    if(unvaluedtradesMap.containsKey(trade.getTradeType())){
    List<String> unValuedTrades = unvaluedtradesMap.get(tradeType);
        unValuedTrades.add(trade.getId());
        unvaluedtradesMap.put(tradeType, unValuedTrades);
    }else{
        unvaluedtradesMap.put(tradeType, Lists.newArrayList(trade.getId()));
    }
}
System.out.println(unvaluedtradesMap);//prints TradeIDS grouped by trade type

}

1 Answer 1

2

You can do this by chaining a mapping collector to groupingBy :

Map<String, List<String>> unvaluedtradesMap 
         = list.stream().collect(Collectors.groupingBy(Trade::getTradeType,
                                                       Collectors.mapping(Trade::getId,
                                                                          Collectors.toList())));
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you... This is awesome!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.