首页 > 解决方案 > 合并 JSON 文件,不包括 JSON 字符串中的重复项

问题描述

我有两个 JSON 字符串students1students2. 我想通过排除重复项来合并这两个字符串。我在 JavaScript 中有以下工作解决方案。如何让它在 Java 中工作?

    const students1=[{studentId: "0001", name: "Joe", class: "1"},{studentId: "0002", name: "john", class: "1"},{studentId: "0003", name: "Max", class: "1"}],
          students2=[{studentId: "0001", name: "Joe", class: "1"},{studentId: "0002", name: "john", class: "1"},{studentId: "0003", name: "Max", class: "1"},{studentId: "0004", name: "Jony", class: "1"}],
          allstudents = Object.values(students1.concat(students2).reduce((r,o) => {
            r[o.studentId] = o;
            return r;
          },{}));
    console.log(allstudents);

标签: javascriptjavajson

解决方案


您可以使用Map数据结构。基本上就像你写的那样,如果学生对象具有相同的studentId.

import java.util.*;

public class HelloWorld{

     public static void main(String []args){
        List<Student> oldStudents = Arrays.asList(new Student("001", "Joe", "1"));
        List<Student> newStudents = Arrays.asList(new Student("001", "john", "2"));
        Map<String, Student> studentMap = new HashMap<>();
        
        for(Student s : oldStudents) {
            studentMap.put(s.studentId, s);
        }
        
        for(Student s : newStudents) {
            studentMap.put(s.studentId, s);
        }
        // If you want to see the output as list
        System.out.println(studentMap.values());
     }
}

class Student {
    String studentId;
    String name;
    String studentClass;
    
    Student(String studentId, String name, String clas) {
        this.studentId = studentId;
        this.name = name;
        this.studentClass = clas;
    }

    @Override
    public String toString() {
        return "Student{studentId: " + studentId + ", name: " + name + ", studentClass: "+ studentClass + "}";
    }
}

推荐阅读