0

I am trying to create a HashMap from an ArrayList of Student objects. I want to pick up alphabets from the name as keys and attach each array list to that key based on the name.

For example, if the input is:

Student{roll no.,Name, Age} {105,Alex,23} {102,Alexander,24} {101,Becky,23} 

The HashMap should be:

{A,{105,Alex,23}}{102,Alexander,24}}{B,{101,Becky,23}}.

My code:

package moduletest;

import java.util.*;
import java.io.*;

class Simple {
    @SuppressWarnings("unchecked")
    public static void main(String args[]) {

        ArrayList al = new ArrayList();
        HashMap<Character, ArrayList<Student>> hm = new HashMap<Character, ArrayList<Student>>();
        al.add(new Student(101, "Vijay", 23));
        al.add(new Student(106, "Ajay", 27));
        al.add(new Student(105, "Jai", 21));

        System.out.println("Sorting ArrayList by Name...");

        Collections.sort(al, new NameComparator());
        Iterator itr = al.iterator();
        while (itr.hasNext()) {
            Student st = (Student) itr.next();
            Character key = st.name.charAt(0);
            hm.put(key, al);
            System.out.println(st.rollno + " " + st.name + " " + st.age);
        }

        System.out.println("HashMap.....");

        for (Map.Entry m : hm.entrySet()) {
            System.out.println(m.getKey() + " " + m.getValue());
        }
        /*
         * Character[] keys = new Character[hm.size()]; Object[] values = new
         * Object[hm.size()]; int index = 0; for (Map.Entry<Character,
         * ArrayList<Student>> mapEntry : hm.entrySet()) { keys[index] =
         * mapEntry.getKey(); values[index] = mapEntry.getValue(); index++; }
         * for(Character chr:keys) { System.out.println(chr); } for(Object
         * value:values) { Iterator itr1 = ((ArrayList) value).iterator(); while
         * (itr1.hasNext()) { Student st1 = (Student) itr1.next();
         * System.out.println(st1.rollno + " " + st1.name + " " + st1.age); } }
         */
    }
}

Output:

Sorting ArrayList by Name...
106 Ajay 27
105 Jai 21
101 Vijay 23
 HashMap.....
V [moduletest.Student@1f5b44d6, moduletest.Student@21044daf, moduletest.Student@21882d18]
A [moduletest.Student@1f5b44d6, moduletest.Student@21044daf, moduletest.Student@21882d18]
J [moduletest.Student@1f5b44d6, moduletest.Student@21044daf, moduletest.Student@21882d18]
1

2 Answers 2

4

That's wrong :

        Character key = st.name.charAt(0);
        hm.put(key, al);

You are putting the entire ArrayList as the value of each of the keys.

You should create a new ArrayList for every key, and put in it only the Students whose name starts with the same character.

        Character key = st.name.charAt(0);
        List l = null;
        if (hm.containsKey(key))
            l = hm.get(key);
        else {
            l = new ArrayList<Student>();
            hm.put(key, l);
        }
        l.add(st);
Sign up to request clarification or add additional context in comments.

Comments

1

Not super efficient, but try something like this...

ArrayList<Student> al = new ArrayList<Student>();
al.add(new Student(101, "Vijay", 23));
al.add(new Student(106, "Ajay", 27));
al.add(new Student(105, "Jai", 21));

Map<Character, ArrayList<Student>> hm = new TreeMap<String, ArrayList<Student>>();

for (Student student : al) {
    Character key = student.name.charAt(0);
    ArrayList<Student> list = hm.get(key);  // get the existing list
    if (list == null) {
        list = new ArrayList<Student>();
    }
    list.add(student);  // add this student to it
    hm.put(key, list);  // replace it in the map, under the correct key
}

the TreeMap will maintain sorted order.

2 Comments

There's no need to replace the entry in the map on each iteration. You only have to call hm.put(key, list) when you create a new list.
@Eran ah yeah... when I originally wrote it, I forgot the null check. I added it later, but didn't change the put.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.