【问题标题】:Cannot map field of cascade list using Java stream()无法使用 Java 流()映射级联列表的字段
【发布时间】:2021-11-03 07:25:25
【问题描述】:

我有一个List<Country>,它有一个List<City>。我想使用 Java 流()检索国家/地区列表中所有城市的 UUID 列表,但我无法正确映射它们。通常我可以获得列表的UUID 字段,但是有级联列表,我找不到合适的解决方案。那么,我该如何解决这个问题呢?我应该使用flatMap吗?

List<UUID> cityUUIDList = countryList.stream().map(CityDTO::getUuid)
    .collect(Collectors.toList());

【问题讨论】:

  • countryList.stream().flatMap(c -&gt; c.getCities().stream()).map(City::getUuid).collect(Collectors.toList());

标签: java list java-stream


【解决方案1】:

你也可以像这样获取UUID的列表:

List<UUID> cityUUIDList = countryList.stream()
        .map(Country::getCities)
        .flatMap(List::stream)
        .map(CityDTO:::getUuid)
        .collect(Collectors.toList());

【讨论】:

    【解决方案2】:

    你需要使用flatMap() 方法,假设你有类似的东西:

    class Country {
        List<CityDTO> cities = new ArrayList<>();
    }
    
    class CityDTO {
        UUID uuid;
        
        UUID getUuid() {
            return uuid;
        }
    }
    
    List<UUID> cityUUIDList = countryList.stream()
                                         .flatMap(c -> c.cities.stream())
                                         .map(CityDTO::getUuid)
                                         .collect(Collectors.toList());
    

    【讨论】:

      猜你喜欢
      • 2011-05-10
      • 1970-01-01
      • 2016-04-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-27
      • 1970-01-01
      相关资源
      最近更新 更多