字符串数组的流转为 JSON 或者哈希映射

huangapple go评论84阅读模式
英文:

Stream of String Array to a Json or Hashmap

问题

{
   "c1" : [1234, 3434, 52, 372],
   "c2" : [887, 7292],
   "c3" : [302]
}
英文:

I have a stream of string arrays and each has a length of two. I would like to convert it into a json after the stream . The first element in the string array is a sort of a key and the second one of its possible values. How can I covert it ?

Input Stream: [c1 , 1234] , [c1, 3434] , [c2 , 887],[c1 , 52] , [c1 , 372],[c2 ,7292], [c3 , 302]..

Output

   {
     "c1" : [1234, 3434, 52,372],
     "c2" : [887, 7292]
     "c3" : [302]
}

答案1

得分: 1

好的,以下是您提供的代码的中文翻译:

这样做是最合理的

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"
  ]
}
英文:

It makes most sense to do it like this:

List&lt;String[]&gt; list = new ArrayList&lt;String[]&gt;();
list.add(new String[] { &quot;c1&quot;, &quot;1234&quot; });
list.add(new String[] { &quot;c1&quot;, &quot;3434&quot; });
list.add(new String[] { &quot;c2&quot;, &quot;887&quot; });
list.add(new String[] { &quot;c1&quot;, &quot;52&quot; });
list.add(new String[] { &quot;c1&quot;, &quot;372&quot; });
list.add(new String[] { &quot;c2&quot;, &quot;7292&quot; });
list.add(new String[] { &quot;c2&quot;, &quot;302&quot; });
Map&lt;String, Set&lt;String&gt;&gt; map = list.stream().collect(
Collectors.toMap(t -&gt; t[0], t -&gt; new HashSet&lt;String&gt;(Arrays.asList(new String[] { t[1] })), (t, u) -&gt; {
t.addAll(u);
return t;
}));

But I'm a bit obsessive about one-liners, so I like to do it like this:

Map&lt;String, Set&lt;String&gt;&gt; map = list.stream()
.collect(Collectors.toMap(t -&gt; t[0],
t -&gt; (Set&lt;String&gt;) new HashSet&lt;String&gt;(Arrays.asList(new String[] { t[1] })),
(t, u) -&gt; Stream.concat(t.stream(), u.stream()).collect(Collectors.toSet())));

Either way, this is the output:

{
&quot;c1&quot;: [
&quot;1234&quot;,
&quot;3434&quot;,
&quot;52&quot;,
&quot;372&quot;
],
&quot;c2&quot;: [
&quot;302&quot;,
&quot;887&quot;,
&quot;7292&quot;
]
}

答案2

得分: 0

这将帮助您入门。

  • 将字符串拆分为 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())));

StringBuilder sb = new StringBuilder("{\n");
map.forEach((k, v) -> sb.append(
        "  \"" + k + "\" : " + v.toString() + ",\n"));
int comma = sb.lastIndexOf(",");
sb.replace(comma, comma + 1, "\n}");

System.out.println(sb);

输出

{
  "c1" : [1234, 3434, 52, 372],
  "c2" : [887, 7292],
  "c3" : [302]
}
英文:

This should get you started.

  • split the string int Cn ### pairs
  • and convert to a map using Cn as the key and a list of ### as the value.
String str =
&quot;[c1 , 1234] , [c1, 3434] , [c2 , 887],[c1 , 52] , [c1 , 372],[c2 ,7292], [c3 , 302]&quot;;
String[] arr = str.replaceAll(&quot;[\\[\\]\\s]&quot;, &quot;&quot;).split(&quot;,&quot;);
Map&lt;String, List&lt;Integer&gt;&gt; map = 
IntStream.iterate(0, i -&gt; i &lt; arr.length, i -&gt; i + 2)
.mapToObj(i -&gt; new String[] { arr[i], arr[i + 1] })
.collect(Collectors.groupingBy(a -&gt; a[0],
TreeMap::new,
Collectors.mapping(
a -&gt; Integer.parseInt(a[1]),
Collectors.toList())));
StringBuilder sb = new StringBuilder(&quot;{\n&quot;);
map.forEach((k, v) -&gt; sb.append(
&quot;  \&quot;&quot; + k + &quot;\&quot;&quot; + &quot; : &quot; + v.toString() + &quot;,\n&quot;));
int comma = sb.lastIndexOf(&quot;,&quot;);
sb.replace(comma, comma + 1, &quot;\n}&quot;);
System.out.println(sb);

Prints

{
&quot;c1&quot; : [1234, 3434, 52, 372],
&quot;c2&quot; : [887, 7292],
&quot;c3&quot; : [302]
}
</details>

huangapple
  • 本文由 发表于 2020年5月5日 00:49:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/61597411.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定