0

I have studied the questions that are about sorting the map, most of those are sorting thap with single key and single values and most of those don't have unique value. Like this question.

I am grouping the list based on the teacherID.

Map<String, List<Assignmentsdata>> result = liveAssignments.stream().collect(Collectors.groupingBy(Assignmentsdata::getTeacherId));

Now students see the assignments added by teachers in the form of groups. but now I want to sort those groups based on the variable totalCompletedAssignments. And now I am lost on how to sort the above map, and at the same time, I don't want multiple loops. Like If a students have not done one assignment at all from teacherA, its place is on top.

Current Output: At index 0 -->TeacherA[(Assignment1->Progress = 10) (Assignment2-> progress 2)] At index 1--> TeacherB[(Assignment1->Progress = 10) (Assignment2-> progress 0)]

Since TeacherB group have an assignment that has 0 progress so far, so it is expected to be at first index like this

Expected OutPut:At index 0--> TeacherB[(Assignment1->Progress = 10) (Assignment2-> progress 0)] At index 1 -->TeacherA[(Assignment1->Progress = 10) (Assignment2-> progress 2)]

Irfan Yaqub
  • 402
  • 4
  • 14
  • What do you expect to get as a result? Hashmap is a structure without an order. Do you want to get sorted List> where first element in pair is the teacher's name and the second one is the corresponding value from an original map? – llesha Apr 02 '23 at 11:44
  • @llesha thanks for the comment, i have updated the question with the expected output. – Irfan Yaqub Apr 02 '23 at 12:57
  • @Yaqub this indeed is impossible, because maps are unsortable structures. There is the [SortedMap](https://docs.oracle.com/javase/7/docs/api/java/util/SortedMap.html), but it sorts entries by keys, not values. – llesha Apr 02 '23 at 13:20

1 Answers1

1

As you probably know, there's no such thing in java as a SortedList but there is a SortedSet.

When using a SortedSet it's important that the Comparator only returns 0 when the items are equal. Let's assume that we can uniquely identify a Assignmentsdata via Assignmentsdata.getId().

In that case, we can do the following:

Comparator<Assignmentsdata> comparator = Comparator
   .comparing(Assignmentsdata::getProgress) // used for sorting
   .thenComparing(Assignmentsdata::getId);  // used when two elements have the same progress

Map<String, SortedSet<Assignmentsdata>> result = liveAssignments
   .stream()
   .collect(Collectors.groupingBy(
      Assignmentsdata::getTeacherId,
      Collectors.toCollection(() -> new TreeSet<>(comparator))
   ));

lance-java
  • 25,497
  • 4
  • 59
  • 101