How to sort such an ArrayList<HashMap<String, String>> productsList; getting data from the network, a piece of code

  protected String doInBackground(Object... args) { List<NameValuePair> params = new ArrayList<NameValuePair>(); // получаем JSON строк с URL params.add(new BasicNameValuePair("pid", pid)); JSONObject json = jParser.makeHttpRequest(url_product_detials, "GET", params); try { // Получаем SUCCESS тег для проверки статуса ответа сервера int success = 0; try { success = json.getInt(TAG_SUCCESS); } catch (JSONException e) { e.printStackTrace(); } if (success == 1) { Log.d("mylog","success"); // продукт найден // Получаем масив из Продуктов products = json.getJSONArray(TAG_PRODUCTS); Log.d("mylog","TAG_PRODUCTS poluchen "); // перебор всех продуктов for (int i = 0; i < products.length(); i++) { JSONObject c = products.getJSONObject(i); // Сохраняем каждый json елемент в переменную String topic_id = c.getString(TOPIC_ID); String forum_id = c.getString(FORUM_ID); String author= c.getString(TOPIC_AUTHOR); String str= c.getString(TOPIC_TITLE); ///reg_X String[] find = {"&", "q", "u","o","t",";"}; for (String temp : find) { str = str.replace(temp, ""); } ///end_reg_x String topic_title = str; // Создаем новый HashMap HashMap<String, String> map = new HashMap<String, String>(); // добавляем каждый елемент в HashMap ключ => значение map.put(TOPIC_ID, topic_id); map.put(FORUM_ID, forum_id); map.put(TOPIC_AUTHOR, author); map.put(TOPIC_TITLE, topic_title); // добавляем HashList в ArrayList productsList.add(map); } } else { } } catch (JSONException e) { e.printStackTrace(); } return null; } /** * После завершения фоновой задачи закрываем прогрес диалог **/ protected void onPostExecute(String file_url) { // закрываем прогресс диалог после получение все продуктов Log.d("mylog","productlist="+productsList.toString()); if(productsList.toArray().length==0){ Log.d("mylog","productlist=null"); Toast.makeText(getActivity(),"В данной ветке нет активных тем",Toast.LENGTH_LONG).show(); // FragmentTransaction ftrans=getFragmentManager().beginTransaction().addToBackStack(TAG); // ftrans.replace(R.id.container, fragmentForumGroup); // ftrans.commit(); } else{ /** * Обновляем распарсенные JSON данные в ListView * */ ListAdapter adapter = new SimpleAdapter( getActivity(), productsList, R.layout.list_item, new String[]{TOPIC_ID, FORUM_ID, TOPIC_TITLE,TOPIC_AUTHOR}, new int[]{R.id.pid, R.id.name, R.id.desc,R.id.author}); Log.d("prefLog","array prodlist"+adapter.toString()); // обновляем listview lv.setAdapter(adapter);} pDialog.dismiss(); } 

at the output I get a listView of how you can sort the list by date, try the alphabet through the collection, feed the adapter productsList or hashmap to it

  • By date? I do not see among the keys display anything like a date. - Sergey Gornostaev
  • Well, according to any of the keys, for example, by author or topic_title alphabetically - dimasta68
  • And why from one Map (JSONObject in fact also Map) to create another? Work with JSONObject, can it be so easier? - Eugene Krivenja

1 answer 1

 Comparator<Map<String, String>> mapComparator = new Comparator<Map<String, String>>() { public int compare(Map<String, String> a, Map<String, String> b) { String aTitle = a.get(TOPIC_TITLE); String bTitle = b.get(TOPIC_TITLE); if(aTitle == null && bTitle == null) return 0; if(aTitle != null && bTitle == null) return -1; if(aTitle == null && bTitle != null) return 1; return aTitle.compareTo(bTitle); } }; Collections.sort(productsList, mapComparator); 

Even easier if the code is written for Android 7

 Comparator<String> nullSafeStringComparator = Comparator.nullsLast(String::compareToIgnoreCase); Collections.sort(productsList, (a, b) -> { return nullSafeStringComparator.compare(a.get("title"), b.get("title")); });