Java 从项返回对象的枚举中获取一组值
我有一个制造类: 然后,我有一个名为Product的枚举,每个项覆盖其抽象方法,该方法返回一个制造实例:Java 从项返回对象的枚举中获取一组值,java,java-8,Java,Java 8,我有一个制造类: 然后,我有一个名为Product的枚举,每个项覆盖其抽象方法,该方法返回一个制造实例: public enum Product { FOO { @Override Manufacture getManufacture(){ return // a instance of Manufacture } } BAR { @Override Manufactur
public enum Product {
FOO {
@Override
Manufacture getManufacture(){
return // a instance of Manufacture
}
}
BAR {
@Override
Manufacture getManufacture(){
return // another instance of Manufacture
}
}
abstract Manufacture getManufacture();
}
我通过以下方式从产品枚举中获取一组制造:
但是steam.map中的方法参考。。。无法链接。您可以链接映射调用,例如:
Set<String> businessIdSet = Stream.of(Product.values())
.map(Product::getManufacture)
.map(Manufacture::getBusinessId).collect(Collectors.toSet());
正如Daniel提到的,您可以链接映射方法 或者,在单个映射中使用lambda也可以实现相同的效果
Set<String> businessIdSet = Stream.of(Product.values())
.map(p-> p.getManufacture().getBusinessId())
.collect(Collectors.toSet());
当您已经知道映射是什么时,只需将getter链接为.mapproduct->product.getManufacture.getBusinessId,您需要使用lambda而不是方法引用。
Set<String> businessIdSet = Stream.of(Product.values()).map(Product::getManufacture::getBusinessId).collect(Collectors.toSet())
Set<String> businessIdSet = Stream.of(Product.values())
.map(Product::getManufacture)
.map(Manufacture::getBusinessId).collect(Collectors.toSet());
Set<String> businessIdSet = Stream.of(Product.values())
.map(p-> p.getManufacture().getBusinessId())
.collect(Collectors.toSet());