How do I compare String HashMap and order them?

Suppose I have a name Mink,Mark,Aashis

. How to compare and arrange them according to alphabetical order. Collections.sort()

Doesn't work for me. This is where I should have results Aashis,Mark and Mark

.

ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map = new HashMap<String, String>();
map.put("name", XMLfunctions.getValue(e, "name"));
                mylist.add(map);

                 Collections.sort( mylist, new Comparator<HashMap<String,String>>(){                    

                    public int compare(HashMap<String, String> lhs,
                            HashMap<String, String> rhs) {
                            //how do i compare string name
                        return 0;

                    }
                 });

      

0


source to share


2 answers


Collections.sort(list, new Comparator(){

public int compare(HashMap<String, String> o1, HashMap<String, String> o2) {
        return (o1.get("name")).compareToIgnoreCase(o2.get("name"));
    }

      

Here "name" is the key you provided when you inserted it into the HashMap using the put method.

EXTRA

If you want to parse double values, you can use the Double.parse () method.



return Double.compare (o1.get (value1), o1.get (value2));

NOTE. The best part about this approach is that you then sort any object by any attribute or even a combination of attributes. For example, if you have objects of type Person with an attribute of income and dataOfBirth, you can define different Comparator implementations and sort the objects according to your needs.

Hope this helps you.

+2


source


try this code

insert values

public ArrayList<HashMap<String, String>> list;
list = new ArrayList<HashMap<String, String>>();

for (int i = 0; i < 5; i++) {

            HashMap<String, String> info = new HashMap<String, String>();

            info.put("title", "gdfgdfgdfgdfggdfgfdgdgdgdffghfghfgh");
            info.put("time", "44:55");
            info.put("view", "54,353");

            list.add(info);

        }

      



get and compare

String title1 = ketan;



for (int i = 0; i < list.size(); i++) {

HashMap<String, String> map = new HashMap<String, String>();
        map = list.get(i);

        if(map.get("title")==title1);
                 {
                    ........
                    ......
                 }      
    }

      

+2


source







All Articles