首页 > 解决方案 > 如何不将重复项添加到数组列表

问题描述

编辑 我没有正确解释自己,所以我会再次正确地问。

我有 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 文件,我希望只将第一个和第三个对象添加到数组中。

标签: javaandroid

解决方案


将您的数组列表传递给(设置)此集合不包含重复项

set<type>  garageSet = new Hashset<type>(garage.getGarage());

推荐阅读