将 Json 数组按照自定义数据在 JAVA 中进行筛选

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

Filter Json Array to custom Data JAVA

问题

这是我第一次使用JSON进行工作,我在尝试过滤一个数组时遇到了困难,我正在尝试获取所有的“Document ID / Page”值。

datalist = {"DocA|1", "DocA|2", "DocA|3", "DocA|4", "DocB|1", "DocB|3", "DocC|1"}
JSONArray jsonObject = json.getJSONArray("datalist");

如何创建筛选值列表?
DocA页面 1,2,3,4
DocB页面 1
DocC页面

英文:

This is my first time working with json and I'm having a hard time trying to filter an array I'm trying to get all values Document ID /Page

datalist = {"DocA|1", "DocA|2, "DocA|3, "DocA|4,, "DocB|1, "DocB|3" , "DocC|1"}
JSONArray jsonObject = json.getJSONArray("datalist");

How to create filter value list ?
DocA page 1,2,3,4
DocB page 1
DocC page

答案1

得分: 0

如果您需要将输入的 String 数组转换为指定的文档 ID 到页码列表的映射,可以使用 Java 8 的 Stream API 来实现,代码如下:

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class Main {

    public static void main(String[] args) {

		String[] input = {"DocA|1", "DocA|2", "DocA|3", "DocA|4", "DocB|1", "DocB|3", "DocC|1"};
        
		Map<String, List<Integer>> data = Arrays.stream(input) // 获取字符串流
              .map(s -> s.split("\\|")) // 使用 | 分隔符将每个字符串拆分成数组
              .collect(Collectors.groupingBy(
                  arr -> arr[0], // 以文档 ID 作为键
                  Collectors.mapping(arr -> Integer.parseInt(arr[1]), Collectors.toList())) // 解析页码并将它们收集到列表中
		);

		System.out.println(data);
    }
}

输出结果为:

{DocA=[1, 2, 3, 4], DocB=[1, 3], DocC=[1]}
英文:

If you need to convert the input array of String into specified map of document IDs to the list of page IDs, this can be implemented as follows using Java 8 Stream API:

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class Main {

    public static void main(String[] args) {

		String[] input = {&quot;DocA|1&quot;, &quot;DocA|2&quot;, &quot;DocA|3&quot;, &quot;DocA|4&quot;, &quot;DocB|1&quot;, &quot;DocB|3&quot;, &quot;DocC|1&quot;};
        
		Map&lt;String, List&lt;Integer&gt;&gt; data = Arrays.stream(input) // get stream of Strings
              .map(s -&gt; s.split(&quot;\\|&quot;)) // split each string into array using | delimiter
              .collect(Collectors.groupingBy(
                  arr -&gt; arr[0], // use documentId as key
                  Collectors.mapping(arr -&gt; Integer.parseInt(arr[1]), Collectors.toList())) // parse page IDs and collect them to list
		);

		System.out.println(data);
    }
}

Output:

{DocA=[1, 2, 3, 4], DocB=[1, 3], DocC=[1]}

huangapple
  • 本文由 发表于 2020年9月16日 16:14:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/63915843.html
匿名

发表评论

匿名网友

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

确定