1

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

3
  • 8
    This sounds like bad design to me. If you want to convert an Object[] to some custom class, then you could add a constructor to the custom class to do this. Commented Jun 7, 2018 at 10:53
  • it can be done with stream reduce. But really, it look like bad design. Commented Jun 7, 2018 at 10:58
  • i tried same thing but here we are setting v to setFName only, i want to set another value to setLName. any other alternative in java8. Here v representing single object. Commented Jun 7, 2018 at 11:01

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Ya i know how to do it in previous version of java before java8, i was looking for if there any direct conversion in java8.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.