I have object array which contain some values. I want to convert this array of object to user defined custom class.
EX : Object[] obj = new Object[4];
obj[0] = "one";
obj[1] = "two";
It is possible to convert this object to Employee object by setting obj[0] to setFName and obj[1] to setLName using stream api of java8. I tried couple of ways but getting error.
output would be
Employee e = Stream.of(Obj).map().....
something like above
If you need to convert Object[]
to Employee
- just do it directly:
Employee e = new Employee();
e.setFirstName(obj[0]);
e.setLastName(obj[1]);
You probably need a special constructor which accepts Object[]
public Employee(Object[] that){
firstName = obj[0];
lastName = obj[1];
}
If you really want to use something from java-8
for some reason, you might use Optional
Employee e = Optional.of(obj).map(o -> {
Employee tmp = new Employee();
tmp.setFirstName(o[0]);
tmp.setLastName(o[1]);
return tmp;
}).get();
But this doesn't give you any advantage over constructor and it is just more confusing. Even if you have the copy constructor variant with Optional
make sense only if obj might be null:
Employee e = Optional.of(obj).map(o -> new Employee(o))
.orElseGet(() -> some default value);
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments