Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 map streams

Is there a way to make this code use Java 8?

public static boolean areBooleansValid(Map<String, Object> pairs, List<String> errors, String... values) {
    for (String value : values) {
        if (pairs.get(value) == null) {
            return false;
        } else if (!(pairs.get(value) instanceof Boolean)) {
            errors.add(value + " does not contain a valid boolean value");
            return false;
        }
    }
    return true;
}

Was thinking something like this:

Stream<Object> e = Stream.of(values).map(pairs::get);

but how can I get it to return the different boolean values from this stream?

like image 506
maloney Avatar asked Aug 27 '26 08:08

maloney


1 Answers

If you just want to filter out the values that are Boolean and present in the pairs map, you can apply filter function:

Stream.of(values).filter(value ->  pairs.get(value) != null && pairs.get(value) instanceof Boolean)

Or if you want to actually return true and false values, you can use map:

return Stream.of(values).allMatch(value -> {
            if (pairs.get(value) == null) {
                return false;
            }
            if ((pairs.get(value) instanceof Boolean)) {
                return true;
            }
            errors.add(value + " does not contain a valid boolean value");
            return false;
        });
like image 70
curlyBraces Avatar answered Aug 28 '26 23:08

curlyBraces