0

How to sort hashmap contains arraylist as a value by key? and also sort arraylist as well?

Hashmap<String, ArrayList<Events>> h = new HashMap<>();
ArrayList<Events> a = new ArrayList<>();
a.add(new Events("1", "name1", "Address1"));
a.add(new Events("2", "name2", "Address2"));
h.put("10-12-2014", a);
h.put("08-11-2014", a1);

... ...

Now I want to sort based on key. and also need to sort ArrayList of each key based on ID.

Raedwald
  • 46,613
  • 43
  • 151
  • 237
Mihir Shah
  • 1,799
  • 3
  • 29
  • 49

5 Answers5

2

Use a TreeMap instead of HashMap, which automatically sorts according to the key's natural order.

To sort the ArrayList, use the static Collections#sort(List, Comparator) method, specifying a comparator to sort the Events objects in the list. For example, assuming you want to sort by the first parameter of the Events constructor called id, then you would call sort as follows:

Map<String, List<Events>> h = new HashMap<>();
List<Events> a = new ArrayList<>();
a.add(new Events("1", "name1", "Address1"));
a.add(new Events("2", "name2", "Address2"));

Collections.sort(a, new Comparator<Events>() {

    @Override
    public int compare(Events o1, Events o2) {
       return o1.getId().compareTo(o2.getId());
    }
});
h.put("10-12-2014", a);

... // similarly for list a1
Collections.sort(a1, new Comparator<Events>() {

    @Override
    public int compare(Events o1, Events o2) {
       return o1.getId().compareTo(o2.getId());
    }
});
h.put("08-11-2014", a1);

Note that it is better to declare the list and map variables to the interfaces, not the implementation, i.e. h is declared of type Map instead of HashMap, and a of type List.

Alternatively, consider putting the Events elements in a TreeSet instead of an ArrayList, and have the Events class implements the Comparable interface:

class Events implements Comparable<Events> {
   private String id;
   ...

   @Override
   public int compareTo(Events o) {
      return this.getId().compareTo(o.getId());
   }
}
M A
  • 71,713
  • 13
  • 134
  • 174
1

To sort an ArrayList, let Events implement Comparable (simply compare the two IDs in the compareTo function) and you can sort it by Collections.sort(a);

I am not sure I understand you HashMap problem correctly, but as manouti said, I would use a TreeMap (a HashMap is usually unsorted by definition)

2mac
  • 111
  • 3
0

aas manouti suggested, use TreeMap for easy sorting of the keys

and for values, just loop through them

    for(Entry<String,List> entry : h.entrySet()){
       ArrayList<Event> a = entry.getValue();
       Collections.sort(entry.getValue());
       h.put(entry.getKey(), a);  //replaces the old value with its sorted value
    }
nafas
  • 5,283
  • 3
  • 29
  • 57
0

Little simple example:

    TreeMap<String,ArrayList<String>> list = new TreeMap<>();
    ArrayList<String> l1 = new ArrayList<>();
    l1.add("hallo");
    l1.add("hello");
    l1.add("yoow");

    ArrayList<String> l2 = new ArrayList<>();
    l2.add("byee");
    l2.add("yooo");
    l2.add("daag");

    list.put("h", l1);
    list.put("e", l2);

    for (String s : list.keySet()){
        Collections.sort(list.get(s));
        System.out.println(list.get(s));
    }

This example is with Strings but if you implement Comparable interface in your object, it should work like this example :-)

Black_Buster
  • 102
  • 5
0

In Java Collections use Custom Sorting. Try implementing Comparator or Comparable interface to your POJO and call Collection's native sort method. For your query i'm writing the below code for sorting custom arraylist for more details use the link in solution :-

public class student {

    private String name = "";
    private int age = 0;

    public void setAge(int age) {
        this.age = age;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public String getName() {
        return name;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final student other = (student) obj;
        if ((this.name == null) ? (other.name != null) : !this.name.equals(other.name)) {
            return false;
        }
        if (this.age != other.age) {
            return false;
        }
        return true;
    }

    @Override
    public int hashCode() {
        int hash = 7;
        hash = 59 * hash + (this.name != null ? this.name.hashCode() : 0);
        hash = 59 * hash + this.age;
        return hash;
    }
}

player class :-

package pojocomparator.mypack;

import java.io.Serializable;
import java.util.Comparator;

public class player implements Comparator<player>{

    private int age = 0;
    private String name = "";
    private student stud = null;

    public player()
    {

    }
    public void setAge(int age) {
        this.age = age;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public String getName() {
        return name;
    }

     public void setStud(student stud) {
        this.stud = stud;
    }

    public student getStud() {
        return stud;
    }   

    /*
     * compare method of Comparator<E> interface used for        comparing object of classes.
     * particularly called by "sort" method of Collections interface
     * @return int
     * @param Class objects for comparison
     */
    @Override
    public int compare(player o1, player o2) {
        return o1.age<o2.age ? -1 :
                o1.age == o2.age ? 0 : 1;
        /*
         * If first object is smaller than second then -1 is returned
         * If first object is equal to second then 0 is returned
         * else 1 is returned.
         */
    }

}


import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class CallAll {

    public static void main(String... q)
    {
        //Generic List of Player class type
        List<player> playerList = new ArrayList<player>();

        player p1 =  new player();
        p1.setAge(21);
        p1.setName("vaibhav");

        player p2 =  new player();
        p2.setAge(18);
        p2.setName("anvesh");

        player p3 =  new player();
        p3.setAge(28);
        p3.setName("rohit");

        playerList.add(p1);
        playerList.add(p2);
        playerList.add(p3);

        /* Below statement is responsible for sorting playerList. This statement 
         * internally calls compare method of Comaparator interface
         */
        Collections.sort(playerList, new player());

        for(int i=0; i<playerList.size(); i++)
        {
            System.out.println(playerList.get(i).getAge());
        }

        // inserting student type object into player type object
        student s1 = new student();
        s1.setName("mickey mouse");
        s1.setAge(15);
        p3.setStud(s1);

        // retrieval of student type data from player type data
        System.out.println("Student name : "+p3.getStud().getName());
        System.out.println("Student age : "+p3.getStud().getAge());
    }
}

gives output :-

run:

18

21

28

Student name : mickey mouse

Student age : 15

BUILD SUCCESSFUL (total time: 6 seconds)

for details refer here:- http://letslearnjava.quora.com/Plain-Old-Java-Object-classes-POJO-Base-for-game-development-EJB-Hibernate-JPA