Reputation: 1663
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?
Upvotes: 3
Views: 347
Reputation: 298599
You can reproduce exactly the same behavior as your original code using
public static boolean areBooleansValid(Map<String, Object> pairs,
List<String> errors, String... values) {
Optional<String> opt = Arrays.stream(values)
.filter(s -> !(pairs.get(s) instanceof Boolean))
.findFirst();
opt .filter(s -> pairs.get(s) != null)
.ifPresent(value -> errors.add(value+" does not contain a valid boolean value"));
return !opt.isPresent();
}
Just like your original code, it just searches for the first item that is not a Boolean
(might be null
), but adds an error only if the value is not null
.
Upvotes: 2
Reputation: 1105
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;
});
Upvotes: 3
Reputation: 728
List<Object> errors = Stream.of(values)
.filter(value -> value == null || !(pairs.get(value) instanceof Boolean))
.collect(Collectors.toList());
List<String> errorMsg = errors.stream().filter(Objects::nonNull)
.map(value -> "" + pairs.get(value) + " does not contain a valid boolean value")
.collect(Collectors.toList());
errors.addAll(errorMsg);
return errors.isEmpty();
Upvotes: 0
Reputation: 60046
I think you need Just :
return Arrays.stream(values)
.allMatch(value -> pairs.get(value) instanceof Boolean);
Notes
error
in your methodpairs.get(value) instanceof Boolean
implies pairs.get(value) != null
so you don't need to use pairs.get(value) != null
Upvotes: 3