Java Streams how do i check for null values and send message while mapping for a new list

Lynx :

So I'm basically trying to figure out if there is a way to avoid having the same code twice and also get key in the place where I'm getting the syntax error.

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

I know that key in the log method is syntax error but I'm wondering how would I be able to access the key in that point and send the message with the key that had the null value? Also is it possible to do all of it while creating the listOfValues in the second stream?

Andronicus :

You can use peek. It evaluates a block of code and continues 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());

If you want to use the key in logging, you can use 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());

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=276827&siteId=1