Giới thiệu
Tương tự bài sắp xếp, nhưng dùng Collections.reverse() để đảo ngược thứ tự phần tử trong list sau khi lấy từ JSON.
Code chính (MainActivity.java)
StringRequest request = new StringRequest(Request.Method.GET, URL,
response -> {
try {
JSONObject obj = new JSONObject(response);
JSONArray array = obj.getJSONArray("users");
List names = new ArrayList<>();
for (int i = 0; i < array.length(); i++) {
names.add(array.getJSONObject(i).getString("name"));
}
Collections.reverse(names); // Đảo ngược thứ tự
textView.setText("Danh sách đảo ngược:\n" + names.toString());
} catch (Exception e) {
e.printStackTrace();
textView.setText("Lỗi");
}
},
error -> textView.setText("Lỗi mạng")
);
queue.add(request);
Giải thích
Collections.reverse(List)đảo ngược thứ tự phần tử trong list in-place (không tạo list mới).- Khác với
Collections.sort()(sắp xếp theo giá trị), reverse chỉ đổi vị trí. - Có thể kết hợp: sort trước, rồi reverse để được thứ tự giảm dần.
Yêu cầu
Cần dependency Volley và quyền INTERNET như các bài trước.