2016-12-06 90 views
2

這個問題被回答爲部分內容here。 我的地圖將按貿易類型分組貿易ID。這個鏈接給我交易按貿易類型分組。我知道我可以進一步操縱它以獲得期望的結果,但只是想知道它是否可能在一個地方。 這是我的代碼。使用流將轉換列表映射到地圖

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 

}

回答

2

您可以通過鏈接一個mapping收藏家groupingBy做到這一點:

Map<String, List<String>> unvaluedtradesMap 
     = list.stream().collect(Collectors.groupingBy(Trade::getTradeType, 
                 Collectors.mapping(Trade::getId, 
                      Collectors.toList()))); 
+0

謝謝......這是真棒! – Surinder

相關問題