java - 如何使用 Java 中的 Streams 在 .map() 中调用函数
问题描述
我java.util.Locale
用来获取国家/地区列表。
我有一个看起来像这样的代码:
List<Country> countries = new ArrayList<>();
String[] countryCodes = Locale.getISOCountries();
for (String countryCode : countryCodes) {
Locale locale = new Locale(language, countryCode);
String code = locale.getCountry();
String name = locale.getDisplayCountry(locale);
try {
countries.add(new Country(code, name));
} catch (IllegalArgumentException e) {
// code and name not valid for creating country. ignore
}
}
return countries;
}
它工作正常。我想转换我在使用 Java Streams 时拥有的代码。
我是这样开始的:
return Stream.of(Locale.getISOCountries())
.map(countryCode -> new Locale(language, countryCode))
.map(c-> new Country(c.getCountry(), c.getDisplayCountry()))
.filter(c-> !(c.getCode().equals("")) && !(c.getName().equals("")))
.collect(Collectors.toList());
但不是这行代码
.map(c-> new Country(c.getCountry(), c.getDisplayCountry()))
我想调用这个函数:
private Optional<Country> createCountry(Locale locale) {
try {
return Optional.of(new Country(locale.getCountry(), locale.getDisplayCountry(locale)));
} catch (IllegalArgumentException e) {
return Optional.empty();
}
我正在考虑做这样的事情:
.map(createCountry(locale))
但是函数和本地不被识别。
我错过了什么?
解决方案
该map
方法接受Function
您向其提供方法调用的结果的时间,即Optional<Country>
. 您需要传入方法参考:
List<Country> countries = Stream.of(Locale.getISOCountries())
.map(countryCode -> new Locale(language, countryCode))
.map(this::createCountry)
.filter(Optional::isPresent)
.map(Optional::get)
.filter(c -> !(c.getCode().equals("")) && !(c.getName().equals("")))
.collect(Collectors.toList());
请注意将 Optional 映射到 a(Country
如果存在)的附加步骤。
推荐阅读
- elasticsearch - Elasticsearch 查询最短匹配
- ruby-on-rails - 如何让 Rails 路由器从内容中动态选择控制器?
- python - 当 Python 写入 CSV 时,脚本在 csv 文件中的 try / except 块中插入新行
- javascript - javascript:作为参数传递时设置不正确的变量
- c++ - 尝试膨胀 png IDAT 块时出现 Z_DATA_ERROR
- laravel - Laravel 使用 assertJson 测试集合 JSON 响应
- java - 无法在 JavaSpring 中自动装配
- excel - 将一列中的数据重新排列为多行
- c++ - 编译时间常数确定
- php - 如何获取特定字符串后的数据