I have a list of Students and I want group this list by the property NAME
, to sort each group ASC
by the property GRADE
, to remove the first entry from each Group and after thatto return the proccesed list.
Here is what I've done.
package com.example.demo;
import java.security.KeyStore.Entry;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class Test {
public static void main(String[] args) {
Student studentA2 = new Student("A", 1);
Student studentA1 = new Student("A", 2);
Student studentA3 = new Student("A", 3);
Student studentA4 = new Student("A", 5);
Student studentA5 = new Student("A", 9);
Student studentB4 = new Student("B", 0);
Student studentB1 = new Student("B", 10);
Student studentB2 = new Student("B", 4);
Student studentB3 = new Student("B", 2);
List<Student> allStudents = new LinkedList<>();
allStudents.addAll(Arrays.asList(studentA1, studentA2, studentA3, studentB1, studentB2, studentB3, studentA4,
studentA5, studentB4));
List<Student> procesedList = doGroupValuesAndRemoveTheSmallestGrade(allStudents);
// The entry: Student("A", 1) and new Student("B", 0) are removed;
procesedList.forEach(x -> System.out.println(x.name + " " + x.grade));
}
private static List<Student> doGroupValuesAndRemoveTheSmallestGrade(List<Student> allStudents) {
Collections.sort(allStudents, Comparator.comparing(Student::getName).thenComparing(Student::getGrade));
Map<String, LinkedList<Student>> groupedStudents = new HashMap<>();
for (Student student : allStudents) {
boolean isNewGroup = groupedStudents.get(student.getName()) == null;
if (isNewGroup) {
groupedStudents.put(student.getName(), new LinkedList<>());
}
groupedStudents.get(student.getName()).add(student);
}
groupedStudents.forEach((k, v) -> v.removeFirst());
List<Student> procesedList = new ArrayList<>();
groupedStudents.forEach((k, childList) -> childList.forEach(student -> procesedList.add(student)));
return procesedList;
}
}
class Student {
public String name;
public int grade;
public Student(String name, int grade) {
super();
this.name = name;
this.grade = grade;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getGrade() {
return grade;
}
public void setGrade(int grade) {
this.grade = grade;
}
}