Java Streams como faço para verificar os valores nulos e enviar mensagem enquanto mapeamento para uma nova lista

Lynx:

Então, eu estou basicamente tentando descobrir se há uma maneira de evitar ter o mesmo código duas vezes e também obter a chave no lugar onde eu estou recebendo o erro de sintaxe.

List<String> listOfKeys = new ArrayList<>(
    Arrays.asList("key1", "key2", "key3", "key4", "key5"));
String path = "something.something.";

listOfKeys.stream()
    .map(key -> path + key)
    .map(getConfig()::getString)
    .forEach(value -> { 
        if (value == null || value.isEmpty()) 
            getLogger().info(key + " is empty"); 
    }); 

List<String> listOfValue = listOfKeys.stream()
    .map(key -> path + key)
    .map(getConfig()::getString)
    .collect(Collectors.toList());

Eu sei que chave no método de log é erro de sintaxe, mas eu estou querendo saber como eu seria capaz de acessar a chave nesse ponto e enviar a mensagem com a chave que tinha o valor nulo? Também é possível fazer tudo isso ao criar o listOfValuesno segundo stream?

Andronicus:

Você pode usar peek. Ele avalia um bloco de código e continua fluindo:

List<String> listOfValue = listOfKeys.stream()
    .map(key -> path + key)
    .map(getConfig()::getString)
    .peek(value -> { 
        if (value == null || value.isEmpty()) 
            getLogger().info(key + " is empty"); 
    })
    .collect(Collectors.toList());

Se você quiser usar a chave de registro, você pode usar Map.Entry:

List<String> listOfValue = listOfKeys.stream()
    .map(key -> new AbstractMap.SimpleEntry(key, getConfig().getString(path + key))
    .peek(entry -> { 
        if (entry.getValue() == null || entry.getValue().isEmpty()) 
            getLogger().info(entry.getKey() + " is empty"); 
    })
    .map(AbstractMap.SimpleEntry::getValue)
    .collect(Collectors.toList());

Acho que você gosta

Origin http://43.154.161.224:23101/article/api/json?id=284217&siteId=1
Recomendado
Clasificación