I am creating a very simple form validation utility for the registration screen, and I encounter unexpected behavior in relation to LinkedHashMap
and the stream created from it entrySet
.
I save the test results in LinkedHashMap
with the following order of statements:
Map<ValidationResult.SignUpField, Boolean> fieldStatuses = new LinkedHashMap<>();
fieldStatuses.put(EMAIL, isValidEmail(emailAddress));
fieldStatuses.put(USERNAME, isValidUsername(username));
fieldStatuses.put(BIRTHDAY, isValidBirthday(birthday));
fieldStatuses.put(PASSWORD, isValidPassword(password));
fieldStatuses.put(CONFIRM_PASSWORD, password.equals(confirmedPassword));
List<ValidationEntry> invalidFields = aggregateInvalidFields(fieldStatuses);
One particular iteration causes all of the above fields to be invalid except for "password confirmation". Using a simple for loop over a set of records and omitting the actual results, invalid results are displayed in the following order:
- Email
- Username
- Birthday
- Password
Then I tried to use a subset of the Stream API available on Android (targeting version 25 with minus 19, hence the absence Collectors.toMap()
):
private static List<ValidationEntry> aggregateInvalidFields(Map<ValidationResult.SignUpField, Boolean> fields) {
List<ValidationEntry> invalidFields = new ArrayList<>();
fields.entrySet()
.stream()
.filter(entry -> !entry.getValue())
.forEachOrdered(entry -> {
ValidationResult.SignUpField field = entry.getKey();
invalidFields.add(new ValidationEntry(field, lookUpErrorCode(field)));
});
return invalidFields;
}
:
, LinkedHashMap
? , forEachOrdered
forEach
, .