Java 8 Lambdas在许多情况下非常有用,以一种紧凑的方式以FP方式实现代码。但是,在某些情况下,我们可能需要访问/修改外部状态,这不符合FP实践标准。(因为Java 8功能接口具有严格的输入和输出签名,我们无法传递额外的参数)
例如:
如何使用Java 8 Streams更加优化地实现相同的功能?
例如:
class Country{
List<State> states;
}
class State{
BigInt population;
String capital;
}
class Main{
List<Country> countries;
//code to fill
}
假设使用案例是获取所有国家所有州的首都列表和人口总数
普通实现:
List<String> capitals = new ArrayList<>();
BigInt population = new BigInt(0);
for(Country country:countries){
for(State state:states){
capitals.add(state.capital);
population.add(state.population)
}
}
如何使用Java 8 Streams更加优化地实现相同的功能?
Stream<State> statesStream = countries.stream().flatMap(country->country.getStates());
capitals = statesStream.get().collect(toList());
population = statesStream.get().reduce((pop1,pop2) -> return pop1+pop2);
但是上述实现不太高效。有没有更好的方法使用Java 8流来操作多个集合?
Stream
上没有get()
方法,流也不能神奇地为你选择正确的属性。 - Holger