How the peek() method works in the Stream api
I have the following code. Explain why in the first call to the map() method, IDEA highlights it and suggests replacing it with peek (). I thought that peek() doesn't change the elements themselves, but apparently it doesn't.
Map<Timestamp, String> sortedNotes = .....
List<String> nodes = sortedNotes.entrySet().stream().map(el -> {
Timestamp time = el.getKey();
String sb = "{\"m\":" + time.getMonth() + ", \"d\":" + time.getDate() + ", \"t\":\"" + el.getValue() + "\"}";
el.setValue(sb);
return el;
}).map(Map.Entry::getValue).collect(Collectors.toList());
1 answers
It is assumed that map()
receives one object as input and returns another. Probably the same type, but different. peek()
is a special case of map()
, which returns the same object that it received at the input, possibly with a modified internal state. Of course, you can use map()
for this, but there are nuances. First, peek()
is one line shorter - you don't need to write return
, Java already knows what to return. Secondly, you are insured against errors - from peek()
it is impossible to return not the object that came to the entrance. Third, you give a hint to those who read your code: "look, only the internal state of the object changes here." It becomes a little easier to read such code. That's why IDEA offers a replacement.