java - 如何不将重复项添加到数组列表
问题描述
编辑 我没有正确解释自己,所以我会再次正确地问。
我有 json 对象的数组列表。我的 json 包含 13000 个对象,每个对象包含几个值。在某些情况下,对象中的值之一是相同的。例如:
这就是我现在所拥有的:
public void readData() {
String json_string = null;
try {
InputStream inputStream = getActivity().getAssets().open("garages.json");
int size = inputStream.available();
byte[] buffer = new byte[size];
inputStream.read(buffer);
inputStream.close();
json_string = new String(buffer, StandardCharsets.UTF_8);
Gson gson = new Gson();
garage = gson.fromJson(json_string, Garage.class);
//In this loop I'm checking address and if it equal to current user address , I'm add this object to Array list.
for (int i = 0; i < 13476; i++) {
if (garage.getGarage().get(i).garageCity.equals(AddressSingleton.getInstance().getCurrentAddress())) {
garageObjects.add(garage.getGarage().get(i));
Log.d("TheDataIS", "readData: " + garage.getGarage().get(i).garageName);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
如果查看 JSON 文件,可以看到第一个和第二个车库中的名称相同,但另一个值garage_code不同。在这种情况下,我不想将两个对象都添加到数组中。
{
"garage" : [
{
"garage_code":16,
"garage_name": "New York Garage",
"phone_number": "123123",
"city":"New York"
},{
"garage_code":21,
"garage_name": "New York Garage",
"phone_number": "123123",
"city":"New York"
},{
"garage_code":51,
"garage_name": "My Garage",
"phone_number": "089898",
"city":"Some city"
},...
对于这个 json 文件,我希望只将第一个和第三个对象添加到数组中。
解决方案
将您的数组列表传递给(设置)此集合不包含重复项
set<type> garageSet = new Hashset<type>(garage.getGarage());
推荐阅读
- javascript - 用于在 javascript 中实现 GUI 编辑器的库或工具(如 figma)
- python - 通过 Python 脚本运行 Powershell 命令不起作用(例如:Set-Location(更改目录))
- azure - 在内联代码连接器逻辑应用中查找 HTML 元素值
- mysql - Mysql系统错误:8 EOF发生违反协议(_ssl.c:877)
- webassembly - WebAssembly 类型化的函数引用不起作用
- python-3.x - 在稳定的 sigmoid 中出现溢出错误
- java - 试图让应用程序从 android 9 运行到 android 11
- android - 知道为什么带有 autoSizeTextType 的 AppCompatTextView (AndroidX) 在平板电脑和 Compat 主题中不起作用吗?
- laravel - Livewire - 我只能将记录添加到数据透视表 - 通过复选框
- python - 使用进度条为 Kivy 应用程序调用顺序线程