-3

I have a class Student with name and department field.

class Student{
    String name;
    String department;
    public Student(String name, String department){
        this.name = name;
        this.department = department;
    }
}

Also I have these sample data in a list-

    List<Student>students = new ArrayList<>();
    students.add(new Student("A", "Science"));
    students.add(new Student("B", "Arts"));
    students.add(new Student("L", "Science"));
    students.add(new Student("C", "Science"));
    students.add(new Student("D", "Science"));
    students.add(new Student("A", "Arts"));
    students.add(new Student("X", "Arts"));
    students.add(new Student("C", "Arts"));

I want them to sort alphabetically in each group so the output will be looks like this-

A, Science
C, Science
D, Science
L, Science
A, Arts
B, Arts
C, Arts
X, Arts

I used comparator and tried to sort the list but it doesn't work. Seems like other solved it using java 8 stream. Could anyone solve it using Stream api.

androidcodehunter
  • 21,567
  • 19
  • 47
  • 70

2 Answers2

2

Using streams would effectively need a comparator as well. Depending on the exact ordering you need (departments first or names first). Should probably make it null safe as well.

List<Student> sortedStudents = students.stream().sorted((o1, o2) -> {
    int depDiff = o1.department.compareTo(o2.department);
    if (depDiff == 0) {
        return o1.name.compareTo(o2.name);
    }
    return depDiff;
}).collect(Collectors.toList());
M21B8
  • 1,867
  • 10
  • 20
0

If I understood correctly, you first need to group by department and keep that sorted in descending order; while the values in each group should be sorted in ascending order.

After the grouping, you need to recreate the List in the order that you specified.

students.stream()
            .collect(Collectors.groupingBy(
                    Student::getDepartment,
                    () -> new TreeMap<>(Comparator.<String> reverseOrder()),
                    Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Student::getName)))))
            .entrySet()
            .stream()
            .flatMap(e -> e.getValue().stream().map(x -> new Student(x.getName(), e.getKey())))
            .collect(Collectors.toList())
Eugene
  • 117,005
  • 15
  • 201
  • 306