# Flattening a map into a list of records

In my everyday work I'm trying to move away from traditional iterating over collections to a more Java 8 streams-like behavior. I'm currently working on a project where I have a collection defined as:

Map<String, <Int, String>> lineBufferMap;


that I would like to iterate through and produce a List<Record>.

My current implementation goes something like this:

Set<Record> l = lineBufferMap
.entrySet().stream()
.flatMap(outer -> e.getValue()
.entrySet().stream()
.map(inner -> createRecord(outer.getKey(), inner.getKey(), inner.getValue())))
.filter(Objects::nonNull)
.collect(Collectors.toSet());


createRecord method:

private Record create(String filename, Long lineNumber, String line) {
Record record = null;
try {
record = new Record(
offsetKey(key),
offsetValue(lineNumber),
topic,
keySchema,
keyStructBuilder.withContent(line).buildStruct(),
valueSchema,
valueStructBuilder.withContent(line).buildStruct());
}catch (ParseException e){
log.error("Malformed line",e);
}
return record;
}


I'm not happy with .filter(Object::nonNull) and haven't come up with a better idea yet.

To add to this problem, the createStruct methods can produce an unchecked parse-exception which in the current solution aborts the whole iteration.

I would prefer it to not break the whole iteration but just to skip the current faulty line and continue with the rest.

This could be considered overcomplicating things as someone suggested but I'm mostly doing it for educational purposes.

• Why would you use forEach here? It only makes it harder. – RobAu Sep 29 '17 at 11:24
• Well, its sort of the best i could come up with. What would you suggest? – Jiinxy Sep 29 '17 at 11:39
• Plain old for loops? Using streams for the sake of using streams should not be your goal . – RobAu Sep 29 '17 at 12:50
• Well in this case is sort of is - for educational purpose :-/ – Jiinxy Sep 29 '17 at 13:08
• What do you mean by "something like"? Is this your real code? Also please show the Record() constructor, so that we can understand the error handling. – 200_success Sep 29 '17 at 13:20