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 listOfValues
no 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());