首页 > 解决方案 > 如何使用 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))

但是函数和本地不被识别。

我错过了什么?

标签: javajava-8stream

解决方案


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如果存在)的附加步骤。


推荐阅读