我有一个字符串数组流,每个都有两个长度。我想在流之后将其转换为json。字符串数组中的第一个元素是一种键,第二个元素是可能的值。我该如何隐秘?
输入流:[c1、1234],[c1、3434],[c2、887],[c1、52],[c1、372],[c2、7292],[c3、302]。
输出
{
"c1" : [1234, 3434, 52,372],
"c2" : [887, 7292]
"c3" : [302]
}
这样做最有意义:
List<String[]> list = new ArrayList<String[]>();
list.add(new String[] { "c1", "1234" });
list.add(new String[] { "c1", "3434" });
list.add(new String[] { "c2", "887" });
list.add(new String[] { "c1", "52" });
list.add(new String[] { "c1", "372" });
list.add(new String[] { "c2", "7292" });
list.add(new String[] { "c2", "302" });
Map<String, Set<String>> map = list.stream().collect(
Collectors.toMap(t -> t[0], t -> new HashSet<String>(Arrays.asList(new String[] { t[1] })), (t, u) -> {
t.addAll(u);
return t;
}));
但是我对一线纸有点着迷,所以我喜欢这样:
Map<String, Set<String>> map = list.stream()
.collect(Collectors.toMap(t -> t[0],
t -> (Set<String>) new HashSet<String>(Arrays.asList(new String[] { t[1] })),
(t, u) -> Stream.concat(t.stream(), u.stream()).collect(Collectors.toSet())));
无论哪种方式,这都是输出:
{
"c1": [
"1234",
"3434",
"52",
"372"
],
"c2": [
"302",
"887",
"7292"
]
}
这应该使您入门。
Cn ###
对拆分Cn
作为键并以###
的列表作为值转换为地图。String str =
"[c1 , 1234] , [c1, 3434] , [c2 , 887],[c1 , 52] , [c1 , 372],[c2 ,7292], [c3 , 302]";
String[] arr = str.replaceAll("[\\[\\]\\s]", "").split(",");
Map<String, List<Integer>> map =
IntStream.iterate(0, i -> i < arr.length, i -> i + 2)
.mapToObj(i -> new String[] { arr[i], arr[i + 1] })
.collect(Collectors.groupingBy(a -> a[0],
TreeMap::new,
Collectors.mapping(
a -> Integer.parseInt(a[1]),
Collectors.toList())));
map.entrySet().forEach(System.out::println);
打印
c1=[1234, 3434, 52, 372]
c2=[887, 7292]
c3=[302]