使用Java 8流ObjectMapper readValue方法



我已经创建了一个方法,该方法遍历String列表并使用ObjectMapper readValue方法将其转换为POJO列表。

public static <T> List<T> mapPayloadListToPOJOList(List<String> payloadList, Class<T> pojo) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    List<T> pojoList = new ArrayList<>();
    for (String payload : payloadList) {
        T mapped = mapper.readValue(payload, pojo);
        pojoList.add(mapped);
    }
    return pojoList;
}
  1. 有一种方法,我可以使用Java 8流,而不是这个实现?
  2. 你能给我一个解决方案吗?

我试图使用map,但它不允许应用Class<T>参数

通过删除for循环并用流代替它可以很容易地做到这一点,但是lambda表达式在处理受控异常时面临一些问题。

您可以使用转换的单独方法来解决它,并在该方法中处理异常(通过记录它或将其作为未检查的异常重新抛出)。

    public static <T> List<T> mapPayloadListToPOJOList(List<String> payloadList, Class<T> pojo) {
        return payloadList.stream()
                          .map(string -> convert(string, pojo))
                          .collect(Collectors.toList());
    }
    public static <T> T convert(String string, Class<T> pojo) {
        ObjectMapper mapper = new ObjectMapper();
        try {
            return mapper.readValue(string, pojo);
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    }

本以为应该是map而不是forEach ..

payloadList.stream()
    .map(s -> mapper.readValue(s, pojo))
    .collect(Collectors.toList())

不同之处在于,map使用提供的lambda (s -> mapper.readValue(s, pojo))将原始List中的每个元素映射到新元素,而forEach对原始List中的每个元素执行副作用而不返回任何内容。

是的,检查这个链接,你可以将列表转换成流,然后用类似

的东西映射每个值
payloadList.stream()
    .forEach( s -> mapper.readValue(s,pojo))
    .collect(Collectors.toList());

相关内容

最新更新