I have a data Map<String, List<Students>> where the key is the subject name.
I want to iterate through each subject and add the score of other subjects corresponding to a student.
I tried the follo
wing:
data.entrySet().stream().forEach(subject -> sumScoresOfAStudent(subject, data));
private void sumScoresOfAStudent(Entry<String, List<Student>> subject, Map<String, List<Student>> data) {
String firstSubject = subject.getKey();
List<Student> firstSubjectScores = subject.getValue();
List<Student> otherSubjectScores = data.entrySet().stream()
.filter(subjectData -> !subjectData.getKey().equalsIgnoreCase(firstSubject))
.map(subjectData -> subjectData.getValue()).flatMap(subjectData -> subjectData.stream())
.collect(Collectors.toList());
...
}
But here I noticed it would loop 3 times for the same data if I have 3 subjects as my Key. Is there any other better way to iterate it only once ?
Thanks in advance for your help.
Eg:
Student s11 = new Student("A", 20);
Student s21 = new Student("B", 10);
data.put("Maths", students);
Student s12 = new Student("A", 30);
Student s22 = new Student("B", 40);
data.put("Science", students);
Student s13 = new Student("A", 45);
Student s23 = new Student("B", 20);
data.put("History", students);
Expected Output :
Student A - 95
Student B - 70