0

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.

Bogdan Kobylynskyi
  • 1,150
  • 1
  • 12
  • 34
  • See also http://stackoverflow.com/questions/504103/how-do-i-write-a-correct-micro-benchmark-in-java – Alexis C. Nov 26 '15 at 21:47
  • 4
    The idiomatic java 8 way is `studentsList.stream().collect(Collectors.toMap(s -> s, Student::getRate))`. You are not recommended to use `forEach` in this way. – Paul Boddington Nov 26 '15 at 21:49
  • Why using `Collectors` is better then `forEach`? – Bogdan Kobylynskyi Nov 26 '15 at 22:00
  • 3
    @BogdanKobylinsky The advice is from Oracle, not me. http://www.oracle.com/webfolder/technetwork/tutorials/moocjdk8/documents/week3/lesson-3-3.pdf Your update about performance is likely to be meaningless without a proper benchmark. However, I suspect your original `for` loop is the most efficient. – Paul Boddington Nov 26 '15 at 22:35
  • In this particular scenario, using a Map does not make any sense. Just use a set of Students and get the rate from the objects directly. Of course, if calculating the rate is a complex calculation, then it's a different matter, but then the overhead from the way you create the map should not really matter. – tobias_k Nov 26 '15 at 22:39

0 Answers0