我有 Map<String, List<String>>
的 map 实现以及一个具有映射键成员变量的 javabean 类。
Java bean 类:
@Data
public class SplunkConfig {
private String parameter1;
private String parameter2;
private String parameter3;
}
map :
{host=["abc","def","ghi","jkl"],count=["1","3","4","5"],time=["2017-02-03","2017-02-04","2017-02-04","2017-02-05"]}
我想在SplunkConfig
中设置变量类如下:
SplunkConfig sc = new SplunkConfig();
sc.setParameter1("abc");
sc.setParameter2("1");
sc.setParameter3("2017-02-03");
sc.setParameter1("def");
sc.setParameter2("3");
sc.setParameter3("2017-02-04");
..so on..
我确实有一个 bean 数组列表,用于在设置变量后存储 Java bean。
因此,我必须逐个循环遍历每个键的映射值并设置 javabean 成员变量,如上所示。
有人可以告诉我如何循环吗?
提前致谢。
最佳答案
首先我们调用带有数据的 map mapWithData,其内容为:
{"host"=["abc","def","ghi","jkl"], "count"=["1","3","4","5"], "time"=["2017-02-03","2017-02-04","2017-02-04","2017-02-05"]}
请注意,键现在是双引号内的字符串。
现在,让我们从该 map 创建一个 SplunkConfig 对象列表:
int numberOfElements = mapWithData.get("host").size();
List<SplunkConfig> config = new ArrayList<SplunkConfig>();
for (int i = 0; i < numberOfElements; i++) {
SplunkConfig sc = new SplunkConfig();
sc.setParameter1(mapWithData.get("host").get(i));
sc.setParameter2(mapWithData.get("count").get(i));
sc.setParameter3(mapWithData.get("time").get(i));
config.add(sc);
}
最好使用描述性名称 - 主机 来调用parameter1。参数2和3相同。
您终于可以使用或返回配置。
关于java - 水平循环Map<String, List<String>>并设置javabean的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43369513/