[英]How to work with Java map with<String, Arraylist<Integer>>
I have a map in java which has String as Key and an integer list as value.我在java中有一个映射,它以字符串为键,以整数列表为值。 My query returns the below set "Day:1, Day:2, Day:3, Month:1, Year:15, Year:20, Year:25"
我的查询返回以下集合“Day:1, Day:2, Day:3, Month:1, Year:15, Year:20, Year:25”
Meaning, I have keys and different values for each keys in random.. I am expecting an output of a map which has unique key and corresponding list of int in values as seen below:意思是,我随机有每个键的键和不同的值。我期待一个映射的输出,它具有唯一的键和对应的 int 值列表,如下所示:
{
"day": [1,2,3],
"Month": [1],
"year": [15,20,25]
}
Kindly help请帮忙
public static void main(String[] args){
String input = "Day:1, Day:2, Day:3, Month:1, Year:15, Year:20, Year:25";
List<String> list = Arrays.asList(input.split(","));
JSONObject jsonObject = new JSONObject();
for (String val : list) {
String[] splitedValues = val.split(":");
if(jsonObject.has(splitedValues[0].trim())) {
jsonObject.getJSONArray(splitedValues[0].trim()).put(Integer.valueOf(splitedValues[1]));
}else {
List<Integer> integers = new ArrayList<Integer>();
integers.add(Integer.valueOf(splitedValues[1]));
jsonObject.put(splitedValues[0].trim(), integers);
}
}
System.out.println(jsonObject);
}
output输出
{"Month":[1],"Year":[15,20,25],"Day":[1,2,3]}
Please find below code.请找到下面的代码。 I have created an inner class to map type and value and then collected it by grouping the type.
我创建了一个内部类来映射类型和值,然后通过对类型进行分组来收集它。
import java.util.Map;
import java.util.stream.Collectors;
import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.toList;
public class StringToMap {
public static void main(String[] args) {
String queryOutput = "Day:1, Day:2, Day:3, Month:1, Year:15, Year:20, Year:25";
System.out.println(groupByTypeAndAddValuesToList(queryOutput));
}
private static Map<String, List<Integer>> groupByTypeAndAddValuesToList(String queryOutput) {
final String[] split = queryOutput.split(",");
return Arrays.stream(split).map(s -> {
final String trimmed = s.trim();
final String[] splitByColon = trimmed.split(":");
return new TypeValues(splitByColon[0], Integer.parseInt(splitByColon[1]));
}).collect(groupingBy(TypeValues::getType, Collectors.mapping(TypeValues::getValue, toList())));
}
private static class TypeValues {
private final String type;
private final Integer value;
public TypeValues(String type, Integer value) {
this.type = type;
this.value = value;
}
public String getType() {
return type;
}
public Integer getValue() {
return value;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.