如何使用Java Stream将Cont对象的ArrayList转换为Map<String,List<String>>
问题:使用Java Stream将Cont对象列表转换为按大洲分组的国家列表Map
现有如下Cont类:
public class Cont { public String getContinent() { return continent; } public void setContinent(String continent) { this.continent = continent; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public Cont(String continent, String country) { super(); this.continent = continent; this.country = country; } String continent; String country; }
在Main方法中初始化了一个Cont对象的ArrayList:
ArrayList<Cont> cList = new ArrayList<Cont>(); cList.add(new Cont("Asia", "China")); cList.add(new Cont("Asia", "India")); cList.add(new Cont("Europe", "Germany")); cList.add(new Cont("Europe", "France")); cList.add(new Cont("Africa", "Ghana")); cList.add(new Cont("Africa", "Egypt")); cList.add(new Cont("South America", "Chile"));
需要将上述列表转换为Map<String, List<String>>结构,其中键为大洲名称,值为对应国家的列表,示例输出如下:
{South America=[Chile], Asia=[China, India], Europe=[Germany, France], Africa=[Ghana, Egypt]}
解决方案
可以通过Java Stream的Collectors.groupingBy结合Collectors.mapping实现分组转换,完整代码如下:
import java.util.ArrayList; import java.util.Map; import java.util.stream.Collectors; public class Main { public static void main(String[] args) { ArrayList<Cont> cList = new ArrayList<Cont>(); cList.add(new Cont("Asia", "China")); cList.add(new Cont("Asia", "India")); cList.add(new Cont("Europe", "Germany")); cList.add(new Cont("Europe", "France")); cList.add(new Cont("Africa", "Ghana")); cList.add(new Cont("Africa", "Egypt")); cList.add(new Cont("South America", "Chile")); // 转换为目标Map结构 Map<String, List<String>> continentCountryMap = cList.stream() .collect(Collectors.groupingBy( // 按大洲名称作为分组键 Cont::getContinent, // 将分组内的Cont对象映射为国家名称,再收集为列表 Collectors.mapping(Cont::getCountry, Collectors.toList()) )); // 打印验证结果 System.out.println(continentCountryMap); } }
代码逻辑说明:
cList.stream():将ArrayList转换为Stream流,开启流式操作Collectors.groupingBy(Cont::getContinent, ...):指定以Cont对象的大洲属性作为分组的键Collectors.mapping(Cont::getCountry, Collectors.toList()):将每个分组内的Cont对象转换为对应的国家名称,并把这些名称收集成List,作为Map对应键的值
运行代码后,即可得到符合要求的分组Map结构。
内容的提问来源于stack exchange,提问作者Shishir Sahay
相关产品推荐
相关产品推荐

