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

}

Community
  • 1
  • 1
curious_soul
  • 559
  • 1
  • 8
  • 29

1 Answers1

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())));
Eran
  • 387,369
  • 54
  • 702
  • 768