如何将列表中的每条信息插入到相关对象中?

How to insert each information, from a list, in the related object?

我收到了一些电话的回复:

{
  "response": [
    {
      "id": "12345678",
      "name": "Name lastName",
      "someBoolean": true
    },
    {
      "id": "987654321",
      "name": "Name2 lastName2",
      "someBoolean": false
    }
  ]
}

该响应插入 class InformationResponse:

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@ToString
@Builder
@EqualsAndHashCode
    public class InformationResponse  {
      private List<Information> info = new ArrayList<>();
    }

class Information 有字段:

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@ToString
@Builder
@EqualsAndHashCode
    public class Information  {
    
      private String id = null;
    
      private String name = null;
    
      private Boolean someBoolean = null;
    
    }

我有一个 context,它必须包含这个 Information class 的列表,但插入了正确的对象。 该 ID 之前已填写,因此我必须比较来自响应的 ID,并将它们插入到我的 context.

中的正确对象中

我的背景class:

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@ToString
@Builder
@EqualsAndHashCode
    public class MyContext {
        private Information clientOne; //id 12345678
        private Information clienteTwo; //id 987654321
    }

那么,如何将响应中的项目插入上下文中的正确对象中?

类似于:

if(myContext.getClientOne().getId().equals(response.getId()) {
  // set the fields here
}

可以实现通过 ID 查找 Information 实例的方法并用于填充上下文:

public static Optional<Information> findInfoById(List<Information> list, String infoId) {
    return list.stream()
               .filter(i -> infoId.equals(i.getId()))
               .findFirst();
}

假设 MyContext class 有一个全参数构造函数,字段可以填充为:

List<Information> infoList = informationResponse.getInfo();

MyContext context = new MyContext(
    findInfoById(infoList, "12345678").orElse(null),
    findInfoById(infoList, "987654321").orElse(null)
);

或使用适当的 getters/setters:

MyContext context; // initialized with clientOne / clientTwo set

List<Information> infoList = informationResponse.getInfo();

findInfoById(infoList, context.getClientOne().getId()).ifPresent(context::setClientOne);
findInfoById(infoList, context.getClientTwo().getId()).ifPresent(context::setClientTwo);