使用流

时间:2016-12-06 08:51:23

标签: java-8 java-stream

这个问题已部分回答here。 我的地图将按贸易类型分组贸易ID。这个链接给了我按tradeType分组的交易。我知道我可以进一步操纵它以获得理想的结果,但只是想知道它是否可以一次性使用。  这是我的代码。

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 个答案:

答案 0 :(得分:2)

您可以将mapping收藏家链接到groupingBy

来执行此操作
Map<String, List<String>> unvaluedtradesMap 
         = list.stream().collect(Collectors.groupingBy(Trade::getTradeType,
                                                       Collectors.mapping(Trade::getId,
                                                                          Collectors.toList())));