英文:
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 = {"DocA|1", "DocA|2", "DocA|3", "DocA|4", "DocB|1", "DocB|3", "DocC|1"};
Map<String, List<Integer>> data = Arrays.stream(input) // get stream of Strings
.map(s -> s.split("\\|")) // split each string into array using | delimiter
.collect(Collectors.groupingBy(
arr -> arr[0], // use documentId as key
Collectors.mapping(arr -> 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]}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论