Search code examples
javapojo

Convert a list of Object values to a POJO


Hi I have the following return value from a dependency. I am trying to convert it to an POJO I represent it with.

Return type structure:

   DependencyAPIResult
     - List<Attribute>

Each Attribute has the following class definition:

public class Attribute {

    @NonNull private final AttributeKey key;
    @NonNull private final AttributeValue value;

    Getters
    .
    .
    .
    Setters
    .
    .
    .
}

I want to map this result to a POJO represented by:

public class MyPOJO {

    private pojoId;
    private pojoName;
    private pojoValue;
}

The way I am currently converting the result to a POJO is like this:

String pojoId = null;
String pojoName = null;
String pojoValue = null;

for (Attribute attribute : result.getAttributes()) {
    switch (attribute.getKey().getName()) {
    case "pojoId"
        id = attribute.getValue().getStringValue();
        break;
    case "pojoName":
        name = attribute.getValue().getStringValue();
        break;
    case "pojoValue":
        pojoValue = attribute.getValue().getStringValue();
        break;
    default:
        break;
    }
}

Is there like an method/mapper or probably Java 8 lambda function which I can use to make this better? Thanks!


Solution

  • You could store them in a Map instead of using a for with a switch :

    Map<String, String> valuesByKeyName = 
    result.getAttributes().stream()
                          .collect(Collectors.toMap(k -> k.getKey().getName(), 
                                   v -> v.getValue().getStringValue()));
    
    String id = valuesByKeyName.get("pojoId");
    String name = valuesByKeyName.get("pojoName");
    String pojoValue = valuesByKeyName.get("pojoValue");
    
    Pojo pojo = new Pojo(id, name, pojoValue);