Skip to content

Instantly share code, notes, and snippets.

@anuvrat
Created August 31, 2015 16:02
Show Gist options
  • Save anuvrat/d0eeb7995d2e34490eb9 to your computer and use it in GitHub Desktop.
Save anuvrat/d0eeb7995d2e34490eb9 to your computer and use it in GitHub Desktop.
/**
* Parse the lines to extract relevant attributes.
* <ul>
* <li>Each line contains only 1 value as key:value</li>
* <li>We are only interested in the attributes that are present in the Attribute enum.</li>
* <li>Name and Country must be present otherwise we'll throw PersonNotFoundException.</li>
* <li>These lines may not have all the attributes. For the missing attributes we'll set the value to NULL</li>
* <li>These lines may contain extra attributes that we are not interested in. Those should be ignored.</li>
* </ul>
*
* @param lines The key:value pair of attribute values that needs to be parsed.
*
* @return The Person object parsed from the lines.
*/
public static Person parsePerson(final List<String> lines) {
// We'll read all the lines and collect the attributes in a map.
final Map<Attribute, List<String>> values =
lines.parallelStream()
.map(l -> l.split(":"))
.filter(a -> a.length == 2)
.filter(a -> Attribute.from(a[0].trim()).isPresent())
.collect(Collectors.groupingBy(a -> Attribute.from(a[0].trim()).get(),
Collectors.mapping(a -> a[1].trim(), Collectors.toList())));
return new Person(getValue(values, Attribute.NAME).orElseThrow(PersonNotFoundException::new),
parseCountry(values).orElseThrow(PersonNotFoundException::new),
getValue(values, Attribute.EMAIL_ADDRESS).orElse(null));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment