I have question about Java 8 from library java.util.Optional.ofNullable;
I have written following code but I hope that it will return value of field of class. But I keep getting toString method from class. What might be cause of behaving this code.
import static java.util.Optional.ofNullable;
public class Main12 {
public static String getName(User user){
return ofNullable(user).map(User::getName).orElse("noFound");
}
public static void main(String[] args) {
User user = new User();
user.setName("ew");
System.out.println(user);
}
}
The result that I get from terminal is User{id=null, name='ew', age=0, roles=[]}.I hope that I will get value of name field from User class.
public class User {
private Long id;
private String name;
private int age;
private Set<Role> roles = new HashSet<>();
public User(long id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
public User(){
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Set<Role> getRoles() {
return roles;
}
public void setRoles(Set<Role> roles) {
this.roles = roles;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
", roles=" + roles +
'}';
}
}
User Class field and methods. When I send null parameter of into method getName from Main12 class. I will get null String but orElse from ofNullable not react what I have written there. Please if you have some idea how to fix it let me know.I never get noFound String or real name of field value of Class.
public String getName() {return name == null ? "notFounf" : name; }- Hadi J