Flujos de Java ¿Cómo puedo comprobar si hay valores nulos y enviar mensajes mientras mapeo para una nueva lista

Lynx:

Así que, básicamente estoy tratando de averiguar si hay una manera de evitar tener el mismo código dos veces y también obtener la llave en el lugar en el que estoy recibiendo el error de sintaxis.

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

Sé que clave en el método de registro es error de sintaxis, pero me pregunto cómo iba a ser capaz de tener acceso a la clave en ese punto y enviar el mensaje con la clave que tuvo el valor nulo? También es posible hacer todo esto mientras se crea la listOfValuesde la segunda corriente?

Andrónico:

Puede usar peek. Se evalúa un bloque de código y continúa el streaming:

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

Si desea utilizar la llave en el registro, puede utilizar 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());

Supongo que te gusta

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