2017-01-16 47 views
3

什么是Java流API替代LambdaJ索引?比方说,我有这样的代码替代LambdaJ索引的Java流

List<Product> products = ... 
Map<Month, Product> productsOnMonths = Lambda.index(products, Lambda.on(Product.class).getMonth()); 

在哪里我知道每个产品都有独特的month属性。

回答

3
products.stream().collect(Collectors.toMap(Product::getMonth, s -> s)); 

这里的区别是,Collectors.toMap可以采取的说如何合并两个条目时,它们是相同的第三个参数;我不认为lambdaj提供那

+0

非常优雅。最后我用了一个带有标识功能的版本。 'product.stream()。collect(Collectors.toMap(Product :: getMonth,Function.identity()));' – Behnil