如何用Java 8 Stream将Information列表转为id为键name为值的Map
问题描述
我有如下代码:
@Embeddable public class Key { @Id private String id; @Id private String name; // getters setters } @Entity public class Information { @EmbeddedId private Key key; // Getters and setters } public class Service { @Autowired private Information information; public InformationResponse service() { List<Information> infot = repo.getInformation(); } }
注:已修正代码中的拼写错误(Embedabble→Embeddable、类名key→Key、字段Name→name、返回类型inforamtionResponse→InformationResponse)
我想要将infot以Map形式存储,以id作为键、name作为值,如何使用Java 8 Stream实现?我尝试过使用Java 8 Stream,但无法从对象中获取对应属性。
解决方案
你可以利用Java 8 Stream的Collectors.toMap()方法完成转换,核心是逐层从Information对象中提取Key的id和name属性——前提是Key和Information类都提供了对应的Getter方法(比如getKey()、getId()、getName())。
具体实现代码如下:
public InformationResponse service() { List<Information> infot = repo.getInformation(); // 转换为以id为键、name为值的Map Map<String, String> idNameMap = infot.stream() .collect(Collectors.toMap( info -> info.getKey().getId(), // 提取Key的id作为Map键 info -> info.getKey().getName() // 提取Key的name作为Map值 )); // 后续业务逻辑示例:将Map放入响应对象 InformationResponse response = new InformationResponse(); response.setIdNameMap(idNameMap); return response; }
额外说明
- 必须保证
Key类的getId()、getName()方法是公开可访问的,否则Stream中无法读取属性值。 - 如果列表中存在重复的
id值,默认的toMap()会抛出IllegalStateException,可以添加第三个参数处理冲突,比如保留第一个出现的值:
Collectors.toMap( info -> info.getKey().getId(), info -> info.getKey().getName(), (existingVal, newVal) -> existingVal // 遇到重复key时保留原有值 )
内容的提问来源于stack exchange,提问作者Niks
相关产品推荐
相关产品推荐

