For example, I have a following code:
Map<Student, Integer> rating = new HashMap<>();
...
for (Student student : studentsList) {
rating.put(student, student.getRate());
}
Can I do the it more efficient using Java 8 tools?
I already tried Java8's forEach
method:
studentsList.forEach(s -> rating.put(s, s.getRate()));
But it seems that it is more expensive. Tests of putting 1M students to the rating
map for both methods show degradation of performance on 10% if we switch to forEach
method (Standart forEach: 250 ms, Java8's forEach: 270 ms)
UPD: Per Paul Boddington's proposal, I tried this:
studentsList.stream().collect(Collectors.toMap(s -> s, Student::getRate))
The result is the least effective among methods above.