I'm trying to understand new functions of java8: forEach and lambda expressions.
Trying to rewrite this function:
public <T extends Object> T copyValues(Class<T> type, T source, T result)
        throws IllegalAccessException
{
    for(Field field : getListOfFields(type)){
        field.set(result, field.get(source));
    }
    return result;
}
using lambda.
I think it should be something like this but can't make it right:
() -> {
     return getListOfFields(type).forEach((Field field) -> {
            field.set(result, field.get(source));
     });
};
                The loop can be replaced by
getListOfFields(type).forEach((field) -> field.set(result, field.get(source)));
However, that forEach method call has no return value, so you still need to 
return result;
separately.
The full method:
public <T extends Object> T copyValues(Class<T> type, T source, T result)
        throws IllegalAccessException
{
    getListOfFields(type).forEach((field) -> field.set(result, field.get(source)));
    return result;
}
EDIT, I didn't notice the issue with the exception. You'll have to catch the exception and throw some unchecked exception. For example:
public <T extends Object> T copyValues(Class<T> type, T source, T result)
{
    getListOfFields(type).forEach (
      (field) -> {
        try {
            field.set(result, field.get(source));
        } catch (IllegalAccessException ex) {
            throw new RuntimeException (ex);
        }
    });
    return result;
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With