我对 flatMap 的了解:
要了解扁平化流的内容,请考虑 像 [[1,2,3],[4,5,6],[7,8,9]] 这样的结构有“两个层次”。 扁平化这意味着将其转换为“一级”结构:[ 1,3,4,6,7,9 ]
import java.util.List;
import java.util.stream.Stream;
public class flatMapDemo {
List<Country> countries;
void demoflatMap(){
Stream<Stream<City>> streamStreamCity = countries
.stream()
.map(country -> country.cities.stream());
streamStreamCity.flatMap(cityStream -> /*it's not City,it's Stream<City> !!!*/);
}
}
class Country{
List<City> cities;
}
class City {
int population;
}
所以我只想计算来自所有国家的所有人口,但在人口超过 1000 的城市中。所以我创建了 Stream<Stream<City>>
并希望 flatMap 为我平铺 Stream<Stream
并给我 City 类采取类似:.flatMap(city -> city.population)
来过滤:.filter(population > 1000)
但似乎我错了。请解释为什么 flatMap 不这样做?不是扁平化的目的吗?