在JSON数组中识别特定元素的重复数值。

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

Identify duplicate values for particular element in a JSON array

问题

在Java中,您可以使用流(Streams)来检查JSON数组中的bookID是否重复。以下是一个示例代码:

import java.util.*;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        String json = "{\"ID\": \"ID1\",\"books\": [{\"bookID\": \"book1\",\"booktype\": \"pdf\"},{\"bookID\": \"book2\",\"booktype\": \"txt\"},{\"bookID\": \"book1\",\"booktype\": \"txt\"}]}";
        
        // 解析JSON字符串为Map
        Map<String, Object> jsonObject = new HashMap<>();
        jsonObject.put("ID1", "ID1"); // 根据您的JSON结构修改
        jsonObject.put("books", Arrays.asList(
            new HashMap<String, Object>() {{
                put("bookID", "book1");
                put("booktype", "pdf");
            }},
            new HashMap<String, Object>() {{
                put("bookID", "book2");
                put("booktype", "txt");
            }},
            new HashMap<String, Object>() {{
                put("bookID", "book1");
                put("booktype", "txt");
            }}
        ));
        
        List<String> bookIDs = ((List<Map<String, Object>>) jsonObject.get("books"))
                .stream()
                .map(book -> (String) book.get("bookID"))
                .collect(Collectors.toList());

        Set<String> duplicateBookIDs = bookIDs.stream()
                .filter(id -> Collections.frequency(bookIDs, id) > 1)
                .collect(Collectors.toSet());

        if (duplicateBookIDs.isEmpty()) {
            System.out.println("No duplicate bookIDs found.");
        } else {
            System.out.println("Duplicate bookIDs: " + duplicateBookIDs);
        }
    }
}

这段代码将解析JSON字符串并使用Java 8流来检查是否有重复的bookID。如果有重复的bookID,它将打印出重复的bookID;否则,它将打印 "No duplicate bookIDs found."。

英文:

JSON array:

{
  &quot;ID : &quot;ID1&quot;,
  &quot;books&quot; : [ {
     &quot;bookID&quot; : &quot;book1&quot;,
     &quot;booktype&quot;: &quot;pdf&quot;
   },{
     &quot;bookID&quot; : &quot;book2&quot;,
     &quot;booktype&quot;: &quot;txt&quot;
   },{
     &quot;bookID&quot; : &quot;book1&quot;,
     &quot;booktype&quot;: &quot;txt&quot;
  }
 ]
}

How to find bookID is duplicated or not here using Java. The JSON array will be big and contains multiple book elements. How to find if any bookID is duplicated?

Expecting an answer in Java 8 using streams or Java.

答案1

得分: 1

以下是代码的中文翻译部分:

// 识别JSON数组中特定元素的重复值:

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class BookIdFind {
    public static void main(String[] args) throws JSONException {
        String jsonString = "{\"ID\": \"ID1\", \"books\": [{\"bookID\": \"book1\", \"booktype\": \"pdf\"}, {\"bookID\": \"book2\", \"booktype\": \"txt\"}, {\"bookID\": \"book1\", \"booktype\": \"txt\"}]}";
        JSONObject jsonObject = new JSONObject(jsonString);
        JSONArray bookArray = jsonObject.getJSONArray("books");
        
        Map<String, List<JSONObject>> booksById = IntStream.range(0, bookArray.length())
                .mapToObj(bookArray::getJSONObject)
                .collect(Collectors.groupingBy(book -> book.getString("bookID")));
        
        List<String> duplicateIds = booksById.values().stream()
                .filter(list -> list.size() > 1)
                .map(list -> list.get(0).getString("bookID"))
                .collect(Collectors.toList());
        
        if (duplicateIds.isEmpty()) {
            System.out.println("未找到重复的图书ID。");
        } else {
            System.out.println("找到重复的图书ID: " + duplicateIds);
        }
    }
}

请注意,这是代码的翻译部分,不包括任何其他内容或问题回答。

英文:

Identify duplicate values for particular element in a JSON array:

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class BookIdFind {
public static void main(String[] args) throws JSONException {
String jsonString = &quot;{ \&quot;ID\&quot; : \&quot;ID1\&quot;, \&quot;books\&quot; : [ { \&quot;bookID\&quot; : \&quot;book1\&quot;, \&quot;booktype\&quot;: \&quot;pdf\&quot; },{ \&quot;bookID\&quot; : \&quot;book2\&quot;, \&quot;booktype\&quot;: \&quot;txt\&quot; },{ \&quot;bookID\&quot; : \&quot;book1\&quot;, \&quot;booktype\&quot;: \&quot;txt\&quot; } ] }&quot;;
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray bookArray = jsonObject.getJSONArray(&quot;books&quot;);
Map&lt;String, List&lt;JSONObject&gt;&gt; booksById = IntStream.range(0, bookArray.length())
.mapToObj(bookArray::getJSONObject)
.collect(Collectors.groupingBy(book -&gt; book.getString(&quot;bookID&quot;)));
List&lt;String&gt; duplicateIds = booksById.values().stream()
.filter(list -&gt; list.size() &gt; 1)
.map(list -&gt; list.get(0).getString(&quot;bookID&quot;))
.collect(Collectors.toList());
if (duplicateIds.isEmpty()) {
System.out.println(&quot;No duplicate book IDs found.&quot;);
} else {
System.out.println(&quot;Duplicate book IDs found: &quot; + duplicateIds);
}
}
}

答案2

得分: 0

你可以在这里了解如何使用Jackson解析JSON。或者你可以将它们解析为对象,然后使用流来检查重复项。

英文:

You can learn more about using Jackson to parse JSON here. Or you can parse them to object and use stream to check for duplicates.

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.HashSet;
import java.util.Set;
public class Main {
public static void main(String[] args) throws JsonProcessingException {
String json = &quot;{ \&quot;ID\&quot; : \&quot;ID1\&quot;, \&quot;books\&quot; : [ { \&quot;bookID\&quot; : \&quot;book1\&quot;, \&quot;booktype\&quot;: \&quot;pdf\&quot; },{ \&quot;bookID\&quot; : \&quot;book2\&quot;, \&quot;booktype\&quot;: \&quot;txt\&quot; },{ \&quot;bookID\&quot; : \&quot;book1\&quot;, \&quot;booktype\&quot;: \&quot;txt\&quot; } ] }&quot;;
ObjectMapper objectMapper = new ObjectMapper();
JsonNode rootNode = objectMapper.readTree(json);
JsonNode booksNode = rootNode.get(&quot;books&quot;);
Set&lt;String&gt; bookIds = new HashSet&lt;&gt;();
booksNode.forEach(bookNode -&gt; {
String bookId = bookNode.get(&quot;bookID&quot;).asText();
if (bookIds.contains(bookId)) {
System.out.println(&quot;Duplicate bookID found: &quot; + bookId);
} else {
bookIds.add(bookId);
}
});
}
}

huangapple
  • 本文由 发表于 2023年2月27日 15:01:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/75577534.html
匿名

发表评论

匿名网友

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

确定