Sriram M
Sriram M

Reputation: 502

Stream.forEach after map operation, why is Object's toString not invoked?

import java.util.*;
import java.nio.file.*;
import java.util.stream.*;
import java.util.function.*;

public class Sample {
    
    public static void main(String[] args) { 
         Stream<Person> stream = Stream.of(new Person("Sriram")); 
     stream.map(p -> p.name = "Ram")
                .forEach(System.out::println); 
  }
}

class Person { 
    String name; 
    Person(String name) { 
         this.name = name; 
  } 
    public String toString() { 
             return "Java"; 
    } 
} 

I expected that the toString method is called at System.out::print in the forEach. So I thought it will always print Java no matter what the name is? But it produces Ram as an output why is it so? much appreciated any reasonable thoughts?

Upvotes: 0

Views: 284

Answers (1)

Naman
Naman

Reputation: 31878

Since the toString is implemented for the instances of Person class, you shall invoke println over the objects of Person type instead of mapping them to their name and then printing the String type.

So something as simple as

stream.forEach(System.out::println);

shall give you the desired output "Java".

Upvotes: 1

Related Questions