javascript - 合并 JSON 文件,不包括 JSON 字符串中的重复项
问题描述
我有两个 JSON 字符串students1
和students2
. 我想通过排除重复项来合并这两个字符串。我在 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);
解决方案
您可以使用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 + "}";
}
}
推荐阅读
- python - 按下时如何在 tkinter 按钮上保留按钮背景和前景色?
- ansible - 剧本中未考虑软件包安装
- python - 通过高斯和多指数衰减卷积进行曲线拟合的 Python 代码
- ruby-on-rails - ActiveRecord:find_by 忽略了自定义 getter
- asp.net-core - 作为 UI 基本 URL 的 ASP.NET Core 标识
- c# - 我可以使用 Invoke 而不是 BeginInvoke 来解决 Dispatcher 处理的暂停问题吗?
- laravel - Laravel 查询意外更新多行
- python - 如何检查列表python中是否包含任何列表元素
- elasticsearch - 如果所有索引都达到 100 GB,如何删除旧的 10 GB 文档?
- java - 如何检查和替换字符串中的字符序列?