You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android开发:如何从JSONArray中移除重复元素并在ListView唯一展示?

Remove Duplicate Elements from JSONArray for ListView Display

Hey there! Let's get those duplicate entries out of your ListView. The key here is to properly identify unique Product items and filter them out during or after parsing your JSON. Here's a step-by-step solution:

1. First, Update Your Product Class

We need to tell Java how to determine if two Product objects are duplicates. Since your JSON uses an id field (which should be unique), we'll override equals() and hashCode() based on this field:

import java.util.Objects;

public class Product {
    private String id;
    private String name;

    public Product(String id, String name) {
        this.id = id;
        this.name = name;
    }

    // Add your getter methods here (required for your adapter)
    public String getId() { return id; }
    public String getName() { return name; }

    // Override equals to compare by id
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Product product = (Product) o;
        return Objects.equals(id, product.id);
    }

    // Override hashCode to match equals logic
    @Override
    public int hashCode() {
        return Objects.hash(id);
    }
}

2. Modify Your JSON Parsing Logic to Filter Duplicates

You have two straightforward options to filter duplicates—pick the one that fits your style:

Option 1: Use a HashSet (Automatic Duplicate Handling)

A HashSet inherently rejects duplicate elements, so we'll use it to collect unique products first, then convert it back to an ArrayList:

@Override
protected void onPostExecute(String content) {
    try {
        JSONObject jsonObject = new JSONObject(content);
        JSONArray jsonArray = jsonObject.getJSONArray("School");
        // Use a HashSet to store unique products
        Set<Product> uniqueProductSet = new HashSet<>();

        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject schoolObj = jsonArray.getJSONObject(i);
            JSONArray namesArray = schoolObj.getJSONArray("Names");
            
            for(int j=0; j<namesArray.length(); j++){
                JSONObject nameObj = namesArray.getJSONObject(j);
                Product product = new Product(
                    nameObj.getString("id"),
                    nameObj.getString("name")
                );
                // HashSet ignores duplicates automatically
                uniqueProductSet.add(product);
            }
        }

        // Convert the set back to ArrayList for your adapter
        arrayList = new ArrayList<>(uniqueProductSet);

    } catch (JSONException e) {
        e.printStackTrace();
    }

    NewtAdapter adapter = new NewtAdapter(
        getApplicationContext(),
        R.layout.list,
        arrayList
    );
    ListView listview = findViewById(R.id.listView);
    listview.setAdapter(adapter);
}

Option 2: Check for Existence Before Adding to ArrayList

If you prefer to stick with just an ArrayList, you can check if the product already exists before adding it (this relies on the equals() method we wrote):

@Override
protected void onPostExecute(String content) {
    try {
        JSONObject jsonObject = new JSONObject(content);
        JSONArray jsonArray = jsonObject.getJSONArray("School");

        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject schoolObj = jsonArray.getJSONObject(i);
            JSONArray namesArray = schoolObj.getJSONArray("Names");
            
            for(int j=0; j<namesArray.length(); j++){
                JSONObject nameObj = namesArray.getJSONObject(j);
                Product product = new Product(
                    nameObj.getString("id"),
                    nameObj.getString("name")
                );
                // Only add if the product isn't already in the list
                if (!arrayList.contains(product)) {
                    arrayList.add(product);
                }
            }
        }

    } catch (JSONException e) {
        e.printStackTrace();
    }

    NewtAdapter adapter = new NewtAdapter(
        getApplicationContext(),
        R.layout.list,
        arrayList
    );
    ListView listview = findViewById(R.id.listView);
    listview.setAdapter(adapter);
}

Quick Notes

  • If you want to consider duplicates based on name instead of id, just adjust the equals() and hashCode() methods to use the name field instead.
  • The HashSet approach is generally more efficient for large datasets, while the contains() check is simpler for small lists.

内容的提问来源于stack exchange,提问作者JackNc

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 04:00:41