Ad Code

How to Sort Array Map in Android Studio Java | Sort List by Name or Numbers

How to Sort Array Map  in Android Studio Java | Sort List by Name or Numbers



Hello Developers,

In this blog I will discuss with you how to sort an Array Map in java. You can use this method in Android Studio for sorting your ListView or RecyclerView. So without wasting your time lets Start.


You can Download this Demo Project from Project Store

SortListMap
public static void sortListMap(final ArrayList<HashMap<String, Object>> listMap, final String key, final boolean isNumber, final boolean ascending) {
        Collections.sort(listMap, new Comparator<HashMap<String, Object>>() {
            public int compare(HashMap<String, Object> _compareMap1, HashMap<String, Object> _compareMap2) {
                if (isNumber) {

                    try {
                        int _count1 = Integer.parseInt(_compareMap1.get(key).toString());
                        int _count2 = Integer.parseInt(_compareMap2.get(key).toString());
                        if (ascending) {
                            return _count1 < _count2 ? -1 : _count1 < _count2 ? 1 : 0;
                        } else {
                            return _count1 > _count2 ? -1 : _count1 > _count2 ? 1 : 0;
                        }
                    } catch (NumberFormatException e) {

                        if (ascending) {
                            return (_compareMap1.get(key).toString()).compareTo(_compareMap2.get(key).toString());
                        } else {
                            return (_compareMap2.get(key).toString()).compareTo(_compareMap1.get(key).toString());
                        }
                    }

                } else {
                    if (ascending) {
                        return (_compareMap1.get(key).toString()).compareTo(_compareMap2.get(key).toString());
                    } else {
                        return (_compareMap2.get(key).toString()).compareTo(_compareMap1.get(key).toString());
                    }
                }
            }
        });
    }

Now, Show the uses of this method


Sort Array Map
      boolean isNumber = true;
      boolean isAscending = true;
      sortListMap(listMap, "your_key",isNumber, isAscending);

Now, You can see an Example of Sort Array Map and use it in ListView or GridView or RecyclerView. First, Create an Activity in your Project.


MainActivity.Java
import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.annotation.SuppressLint;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Locale;

public class MainActivity extends AppCompatActivity {

    ArrayList<HashMap<String, Object>> listMap = new ArrayList<>();
    Button sort_by_name, sort_by_number;
    RecyclerView recyclerView;

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

        sort_by_name = findViewById(R.id.sort_by_name);
        sort_by_number = findViewById(R.id.sort_by_number);
        recyclerView = findViewById(R.id.recyclerview1);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        loadMap();

        sort_by_number.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                sortListMap(listMap, "Number", true, true);

                recyclerView.setAdapter(new Recyclerview1Adapter(listMap));

            }
        });

          sort_by_name.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                sortListMap(listMap, "Name", false, true);

                recyclerView.setAdapter(new Recyclerview1Adapter(listMap));
            }
        });




    }


    private void loadMap() {

        HashMap<String, Object> map = new HashMap<>();
        map.put("Name", "Anika");
        map.put("Number", "5");
        listMap.add(map);

        HashMap<String, Object> map2 = new HashMap<>();
        map2.put("Name", "Rahul");
        map2.put("Number", "3");
        listMap.add(map2);

        HashMap<String, Object> map3 = new HashMap<>();
        map3.put("Name", "Salman");
        map3.put("Number", "2");
        listMap.add(map3);

        HashMap<String, Object> map4 = new HashMap<>();
        map4.put("Name", "Aman");
        map4.put("Number", "4");
        listMap.add(map4);

        HashMap<String, Object> map5 = new HashMap<>();
        map5.put("Name", "Karan");
        map5.put("Number", "1");
        listMap.add(map5);



        recyclerView.setAdapter(new Recyclerview1Adapter(listMap));

    }


    public static void sortListMap(final ArrayList<HashMap<String, Object>> listMap, final String key, final boolean isNumber, final boolean ascending) {
        Collections.sort(listMap, new Comparator<HashMap<String, Object>>() {
            public int compare(HashMap<String, Object> _compareMap1, HashMap<String, Object> _compareMap2) {
                if (isNumber) {

                    try {
                        int _count1 = Integer.parseInt(_compareMap1.get(key).toString());
                        int _count2 = Integer.parseInt(_compareMap2.get(key).toString());
                        if (ascending) {
                            return _count1 < _count2 ? -1 : _count1 < _count2 ? 1 : 0;
                        } else {
                            return _count1 > _count2 ? -1 : _count1 > _count2 ? 1 : 0;
                        }
                    } catch (NumberFormatException e) {

                        if (ascending) {
                            return (_compareMap1.get(key).toString()).compareTo(_compareMap2.get(key).toString());
                        } else {
                            return (_compareMap2.get(key).toString()).compareTo(_compareMap1.get(key).toString());
                        }
                    }

                } else {
                    if (ascending) {
                        return (_compareMap1.get(key).toString()).compareTo(_compareMap2.get(key).toString());
                    } else {
                        return (_compareMap2.get(key).toString()).compareTo(_compareMap1.get(key).toString());
                    }
                }
            }
        });
    }


    public class Recyclerview1Adapter extends RecyclerView.Adapter<MainActivity.Recyclerview1Adapter.ViewHolder> {
        ArrayList<HashMap<String, Object>> _data;


        public Recyclerview1Adapter(ArrayList<HashMap<String, Object>> _arr) {
            _data = _arr;

        }

        @Override
        public MainActivity.Recyclerview1Adapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            LayoutInflater _inflater = (LayoutInflater) getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View _v = _inflater.inflate(R.layout.list_adapter, null);

            RecyclerView.LayoutParams _lp = new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            _v.setLayoutParams(_lp);

            return new MainActivity.Recyclerview1Adapter.ViewHolder(_v);


        }

        @SuppressLint("SetTextI18n")
        @Override
        public void onBindViewHolder(MainActivity.Recyclerview1Adapter.ViewHolder _holder, @SuppressLint("RecyclerView") final int _position) {
            View _view = _holder.itemView;


            TextView nameText = _view.findViewById(R.id.nameText);
            TextView numberText = _view.findViewById(R.id.numberText);

            nameText.setText("Name :".concat(_data.get(_position).get("Name").toString()));
            numberText.setText("Number :".concat(_data.get(_position).get("Number").toString()));


        }

        @Override
        public int getItemCount() {
            return _data.size();
        }

        public class ViewHolder extends RecyclerView.ViewHolder {
            public ViewHolder(View v) {
                super(v);
            }
        }


    }
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_margin="8dp"
        android:orientation="vertical"
        android:layout_height="match_parent">



        <LinearLayout
            android:layout_width="match_parent"
            android:gravity="center"
            android:layout_height="wrap_content">

            <Button
                android:id="@+id/sort_by_name"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginRight="4dp"
                android:text="Sort_by_Name"/>


             <Button
                android:id="@+id/sort_by_number"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                 android:layout_marginLeft="4dp"
                android:text="Sort_by_Number"/>



        </LinearLayout>




        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/recyclerview1"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>


    </LinearLayout>






</androidx.constraintlayout.widget.ConstraintLayout>

Here is the Adapter Layout which is used for Recyclerview Adapter

list_adapter.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.cardview.widget.CardView
        android:layout_width="match_parent"
        android:layout_margin="8dp"
        android:layout_height="wrap_content">

      <LinearLayout
          android:layout_width="match_parent"
          android:orientation="vertical"
          android:layout_margin="8dp"
          android:layout_height="wrap_content">

          <TextView
              android:id="@+id/nameText"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:text="Name :"/>
            <TextView
              android:id="@+id/numberText"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:text="Number :"/>


      </LinearLayout>

    </androidx.cardview.widget.CardView>

</LinearLayout>

If you want to Download this Project then You can Download this Demo Project from Project Store. Do not forget to visit our Youtube chennal for geting Amazing Android Projects.







Thank You

Post a Comment

0 Comments

Ad Code