Java 8 使用 Stream API 将 List 转换为 Map<String, List>

假设 Person 类中有一个属性为 'name',可以使用 Java 8 的 Stream API 将 List 转换为 Map<String, List>,其中 List 包含每个 Person 对象的 'name' 属性作为元素。

代码示例

Map<String, List<String>> map = personList.stream()
        .collect(Collectors.groupingBy(Person::getName,
                Collectors.mapping(p -> p.getKey(), Collectors.toList())));

解释

  1. 首先使用 Stream 的 groupingBy() 方法将 List 按照 'name' 属性分组,得到一个 Map<String, List>,其中 key 为 'name' 属性值,value 为具有相同 'name' 属性值的 Person 对象列表。

  2. 然后使用 mapping() 方法将每个 Person 对象映射为其 'name' 属性值,并使用 toList() 方法将其转换为 List

  3. 最终得到 Map<String, List>,其中每个 key 为 'name' 属性值,value 为包含具有相同 'name' 属性值的 Person 对象的 'name' 属性的 String 列表。


原文地址: https://www.cveoy.top/t/topic/nlLO 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录