split , , . , , BufferedReader.
Java 8:
static String memoText = "foo: fooValue\r\n" +
"otherKey: otherValue\r\n" +
"# something else like a comment line\r\n" +
"bar: barValue\r\n";
static Map<String, String> parseKeysValues(String memoText) {
Pattern pattern = Pattern.compile("([a-zA-Z]+)\\s*:\\s*(.*)");
Set<String> allowedKeys = new HashSet<>(Arrays.asList("foo", "bar"));
return new BufferedReader(new StringReader(memoText)).lines()
.map(pattern::matcher)
.filter(Matcher::matches)
.filter(m -> allowedKeys.contains(m.group(1)))
.collect(Collectors.toMap(m -> m.group(1), m -> m.group(2)));
}
, , , , . , , , .. filter(Matcher::matches) . 1 , 2 - , , .
, . , toMap, . , (a, b) -> b " ".
Java 9 :
static Map<String, String> parseKeysValues9(String memoText) {
Set<String> allowedKeys = Set.of("foo", "bar");
return new Scanner(memoText).findAll("(?m)^([a-zA-Z]+)\\s*:\\s*(.*)$")
.filter(mr -> allowedKeys.contains(mr.group(1)))
.collect(Collectors.toMap(mr -> mr.group(1), mr -> mr.group(2), (a, b) -> b));
}
Set.of static factory. Scanner BufferedReader. findAll MatchResult, . , , , . ^ $ . (?m), MULTILINE, ^ $ , . , , , . toMap.