使用MapStruct将值为CSV格式的Map转换为Set<String>集合方法咨询
MapStruct HashMap转自定义Set类型实现方案
首先明确前置条件:已正确引入MapStruct核心及注解处理器依赖,MapValue为自定义包装类,此处假设该类提供对应类型的单参数构造方法,且已重写equals、hashCode方法适配Set存储规则,示例MapValue结构如下:
public class MapValue { // 示例为String类型,可根据实际需求调整为Integer等其他类型 private String value; // 全参构造、getter、setter、equals、hashCode、toString方法省略 }
实现步骤
- 定义MapStruct Mapper接口,内置自定义转换逻辑:
import org.mapstruct.Mapper; import org.mapstruct.Mapping; import org.mapstruct.Named; import java.util.Arrays; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; // 若使用Spring容器管理,添加componentModel = "spring"配置,否则可删除该参数 @Mapper(componentModel = "spring") public interface HashmapToModelMapper { // 指定映射规则:取HashMap中Key为Key1的值,用自定义方法转换后赋值给myvalues属性 @Mapping(source = "Key1", target = "myvalues", qualifiedByName = "strToMapValueSet") Model convert(Map<String, String> sourceMap); // 自定义转换方法:将逗号分隔的字符串转换为Set<MapValue> @Named("strToMapValueSet") default Set<MapValue> convertStrToSet(String str) { if (str == null || str.trim().isEmpty()) { return Set.of(); } return Arrays.stream(str.split(",")) .map(String::trim) // 若MapValue存储的是数值类型,可在此处增加Integer::valueOf等转换逻辑 .map(MapValue::new) .collect(Collectors.toSet()); } }
- 直接调用Mapper方法完成转换:
// 示例调用代码,未使用Spring框架可直接调用Mapper实例 Map<String, String> source = Map.of("Key1", "1, 2, 3, 4"); Model model = HashmapToModelMapper.INSTANCE.convert(source); // 输出model.getMyvalues()即可得到[1, 2, 3, 4]的预期效果
内容的提问来源于stack exchange,提问作者Timo
相关产品推荐
相关产品推荐

