Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Android

Cách loại bỏ trùng lặp trong mảng JSON Volley Android

Giới thiệu

Sử dụng HashSet để loại bỏ đối tượng trùng lặp sau khi parse JSON, kết hợp sắp xếp theo ID.

Code chính (MainActivity.java)

public class MainActivity extends AppCompatActivity {

    private TextView textView;
    private RequestQueue queue;
    private static final String URL = "https://mocky.io/v2/597c41390f0000d002f4dbd1";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textView = findViewById(R.id.text);
        queue = Volley.newRequestQueue(this);

        StringRequest request = new StringRequest(Request.Method.GET, URL,
            response -> {
                try {
                    JSONObject obj = new JSONObject(response);
                    JSONArray array = obj.getJSONArray("users");
                    List list = new ArrayList<>();

                    for (int i = 0; i < array.length(); i++) {
                        JSONObject u = array.getJSONObject(i);
                        list.add(new UserInfo(u.getString("name"), u.getString("id")));
                    }

                    // Sắp xếp theo ID
                    Collections.sort(list, Comparator.comparing(o -> o.id));

                    // Loại trùng lặp bằng HashSet (cần override equals/hashCode)
                    HashSet set = new HashSet<>(list);
                    list.clear();
                    list.addAll(set);

                    UserInfo first = list.get(0);
                    textView.setText("ID: " + first.id + "\nName: " + first.name);
                } catch (Exception e) {
                    e.printStackTrace();
                    textView.setText("Lỗi");
                }
            },
            error -> textView.setText("Lỗi mạng")
        );

        queue.add(request);
    }

    // Phải override equals & hashCode để HashSet hoạt động đúng
    private static class UserInfo {
        String name, id;
        UserInfo(String name, String id) { this.name = name; this.id = id; }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (!(o instanceof UserInfo)) return false;
            UserInfo that = (UserInfo) o;
            return id.equals(that.id); // coi trùng nếu ID giống nhau
        }

        @Override
        public int hashCode() {
            return id.hashCode();
        }
    }
}

Giải thích

  • HashSet không cho phép phần tử trùng lặp (dựa trên equals() và hashCode()).
  • Phải override cả hai phương thức trong class model, ở đây coi trùng khi id giống nhau.
  • Thứ tự sau khi addAll từ HashSet không đảm bảo, nên sắp xếp lại nếu cần.