从地图列表中提取所有字符串值

我收到以下格式的休息回复。

{
    "query_result": {
        "status": "SUCCESS","message": "Results Found","results": [
            {
                "key": "123"
            },{
                "key": "465"
            }
        ]
    }
}

从这个响应中,我想从键创建一个字符串列表。 因此希望获得如下列表结果:

["123","456"]

尝试按如下方式生成输出,但卡在以下代码块中的映射步骤。

public Optional<List<String>> get(HttpEntity<Request> request){
    ResponseEntity<Response> response = getResponse(request); // this response holds above json data 

    return Optional.ofNullable(response)
            .map(ResponseEntity::getBody)
            .map(Response::getQueryResult)
            .map(QueryResult::getResults)
            .filter(CollectionUtils::isnotEmpty)
            .map(results -> results.) // Stuck here. results here is the list of results shown in above json. 
}

我无法从这里提取所有键的值。 我最终不得不按如下方式指示索引,这将不起作用,因为我想要所有键。

.map(results -> results.get(0))

尝试考虑使用迭代器,但最终只会捕获第一个键。

.filter(CollectionUtils::isnotEmpty)
.map(List::iterator)
.map(Iterator::next)
.map(result -> result.getKey())

我能帮我解决这个问题吗?谢谢。

z4521215 回答:从地图列表中提取所有字符串值

.map(QueryResult::getResults)
.filter(CollectionUtils::isNotEmpty)
.map(results -> results.stream().map(Key::getKey).collect(Collectors.toList()));

假设每个关键对象都正确映射到一个名为 Key 的类,如下所示:

class Key {
    String key;

    String getKey() {
        return key;
    }
}

您希望在 Optional 链上将其内部 Key 列表转换为 String 列表。所以最后一步只处理那部分。

注意
  1. 您的方法返回一个可选列表。一般来说,如果您返回一个空列表而不是 null 在语义上会更好,但这取决于实现。

  2. 如果越来越难以理解 lambda,请将其逻辑移至方法。例如上面的链可以变成:

List<String> collectKeys(List<Key> keys) {
    return keys.stream().map(Key::getKey).collect(Collectors.toList())
}

// and then:
.map(QueryResult::getResults)
.filter(CollectionUtils::isNotEmpty)
.map(this::collectKeys);
本文链接:https://www.f2er.com/5505.html

大家都在问