Need help to simplify the solution

Viewed 57

I am learning Java and doing some operation related to HashMap. I am trying to add details in hashmap based on city. So suppose below is the list we have

List<Student> studentList= new LinkedList<>();
    studentList.add(new Student(1, "Test1", "US"));
    studentList.add(new Student(2, "Test2", "US"));
    studentList.add(new Student(3, "Test3", "India"));
    studentList.add(new Student(4, "Test4", "Canada"));
    studentList.add(new Student(5, "Test5", "Canada"));
    studentList.add(new Student(6, "Test6", "India"));

For this my output is something like below:

{US=[Test1, Test2], India=[Test3, Test6], Canada=[Test4, Test5]}

I have implemented the code for this but it's time complexity is very high so looking for some optimize solution.

private void getDetailsGroupByCity(List<Student> studentList)
{
    Map<String,ArrayList<String>> studentHashMap= new HashMap<>();
    List<Student> arrayList= new ArrayList<>(studentList);
    List<String> names= new ArrayList<>();

    Set<String> setKey= new HashSet<>();
    for (Student student : arrayList) {
        setKey.add(student.getCity());
    }
    for (String s : setKey) {
        for (Student student : arrayList) {
            if (s==student.getCity())
            {
                names.add(student.getName());
                studentHashMap.put(s, (ArrayList<String>) names);
            }
        }
        names= new ArrayList<>();
    }

    System.out.println(studentHashMap);
}
1 Answers

You only need to go over the student list once, and assign each student to the right place in the map as you go, resulting in an O(n) solution:

Map<String, List<String>> studentHashMap = new HashMap<>();
for (Student s : studentList) {
    studentHashMap.computeIfAbsent(s.getCity(), k => new ArrayList<>()).add(s.getName);
}

You could also achieve the same result by using streams, although I'm not sure this would indeed be more elegant:

Map<String, List<String>> studentMap =
    studentList.stream()
               .collect(Collectors.groupingBy(
                                     Student::getCity,
                                     Collectors.mapping(
                                                  Student::getName, 
                                                  Collectors.toList())));
Related