我是Java的新手,我通过使用带有for循环和if语句的单个arraylist来制作Follow json,但是我坚持使用for循环逻辑部分。
这是我的Java程序。
main.java
公共静态void main(String args [])引发JsonProcessingException {
List<Map<Object, Object>> dataProviderList = new LinkedList<>();
List<Object> yearList = new LinkedList<>();
yearList.add(2009);
yearList.add(2010);
yearList.add(2011);
yearList.add(2012);
yearList.add(2013);
yearList.add(2014);
yearList.add(21.4);
yearList.add(31.3);
yearList.add(15.6);
yearList.add(34.8);
yearList.add(20.1);
yearList.add(27.3);
yearList.add(20.3);
yearList.add(43.1);
yearList.add(19.8);
yearList.add(34.7);
yearList.add(24.4);
yearList.add(21.9);
for (int i = 0; i < (yearList.size() - (i + 6)); i++) {
Map<Object, Object> dataProviderValueMap = new LinkedHashMap<>();
dataProviderValueMap.put("year", yearList.get(i));
for (int j = 0; j < (yearList.size() + (i - 6)); j++) {
dataProviderValueMap.put("income", yearList.get(j));
for (int k = 0; k < (yearList.size() + (i - 6)); k++) {
dataProviderValueMap.put("expenses", yearList.get(k));
// for year 2014
if (k == (yearList.size() - 2)) {
dataProviderValueMap.put("dashLengthLine", 0);
dataProviderValueMap.put("dashLengthColumn", 5);
dataProviderValueMap.put("alpha", 0.5);
dataProviderValueMap.put("additional", "(projection)");
}
// for year 2013
if (k == (yearList.size() - 3)) {
dataProviderValueMap.put("dashLengthLine", 5);
}
}
}
dataProviderList.add(dataProviderValueMap);
}
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
String mapToJson = objectMapper.writeValueAsString(dataProviderList);
System.out.println(mapToJson);
}
我想要以下输出:
所需的输出:
“ dataProvider”:[{
“年”:2009年,
“收入”:21.4,
“费用”:20.3
},{
“年”:2010年,
“收入”:31.3,
“费用”:43.1
},{
“年”:2011年,
“收入”:15.6,
“费用”:9.8
},{
“年”:2012年,
“收入”:34.8,
“费用”:34.7
},{
“年”:2013年,
“收入”:20.1,
“费用”:24.4,
“ dashLengthLine”:5
},{
“年”:2014年,
“收入”:27.3,
“费用”:21.9,
“ dashLengthLine”:0,
“ dashLengthColumn”:5
“ alpha”:0.5,
“ additional”:“(投影)”
}]
我如何才能使此循环更具体并增强for循环? 我只想使用一个arraylist和for循环,并且if语句在for循环中包含Map。 谢谢您的帮助!
java for循环if语句arraylist动态