如何提取CollectiveInterestsRes中targetInfo的指定键值对并打印
问题与解决方案
问题描述
已通过以下代码获取到CollectiveInterestsRes对象中的targetInfo列表:
List<Map<String, String>> targetInfo = collectiveInterestsRes.get(0).getTargetInfo();
需要完成:
- 获取
targetInfo中的前3个元素(该列表最多包含3个元素) - 提取
entertainment_interest_f、citizenship_s、tv_interest_f这三个变量及其对应值,打印到控制台
相关参考
实例结构
CollectiveInterestsRes( targetInfo=[{entertainment_interest_f=3.0}, {citizenship_s->America=3.0}, {tv_interest_f=3.0}], msisdnCount=3, msisdnList=[495012072622, 495012103468, 495012115405], isSuccess=true, ruleRequests=[RuleRequest(ruleId=tv, subruleId=null, locationRequest=null, operator=EQ, values=[1], msisdnRequest=null)] )
类定义
public class CollectiveInterestsRes { private List<Map<String,String>> targetInfo; private Integer gsmNoCount; private List<String> gsmNoList; private boolean isSuccess; private List<RuleRequest> ruleRequests; }
实现代码
import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; // 1. 截取前3个元素(兼容列表长度不足3的情况) List<Map<String, String>> top3TargetInfo = targetInfo.subList(0, Math.min(targetInfo.size(), 3)); // 2. 定义需要提取的目标变量名称 Set<String> targetKeys = new HashSet<>(Arrays.asList( "entertainment_interest_f", "citizenship_s", "tv_interest_f" )); // 3. 遍历提取并打印目标变量 for (Map<String, String> infoMap : top3TargetInfo) { for (Map.Entry<String, String> entry : infoMap.entrySet()) { String currentKey = entry.getKey(); String currentValue = entry.getValue(); // 处理citizenship_s的特殊格式(实例中键为"citizenship_s->America") if (currentKey.startsWith("citizenship_s->")) { String citizenshipValue = currentKey.split("->", 2)[1]; System.out.printf("citizenship_s: %s(权重:%s)%n", citizenshipValue, currentValue); } else if (targetKeys.contains(currentKey)) { System.out.printf("%s: %s%n", currentKey, currentValue); } } }
代码说明
- 截取前3个元素时使用
Math.min(targetInfo.size(), 3),避免列表长度不足3时抛出IndexOutOfBoundsException - 针对实例中
citizenship_s的特殊存储格式(键包含->),通过字符串拆分提取实际的国籍值,同时保留权重值 - 使用
Set存储目标变量名称,提高键的判断效率
内容的提问来源于stack exchange,提问作者sticky fingers
相关产品推荐
相关产品推荐

