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
    .flatMap(outer -> e.getValue()
            .map(inner -> createRecord(outer.getKey(), inner.getKey(), inner.getValue())))                                                             

createRecord method:

private Record create(String filename, Long lineNumber, String line) {
    Record record = null;
    try {
        record = new Record(
    }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.

  • \$\begingroup\$ Why would you use forEach here? It only makes it harder. \$\endgroup\$ – RobAu Sep 29 '17 at 11:24
  • \$\begingroup\$ Well, its sort of the best i could come up with. What would you suggest? \$\endgroup\$ – Jiinxy Sep 29 '17 at 11:39
  • \$\begingroup\$ Plain old for loops? Using streams for the sake of using streams should not be your goal . \$\endgroup\$ – RobAu Sep 29 '17 at 12:50
  • \$\begingroup\$ Well in this case is sort of is - for educational purpose :-/ \$\endgroup\$ – Jiinxy Sep 29 '17 at 13:08
  • \$\begingroup\$ 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. \$\endgroup\$ – 200_success Sep 29 '17 at 13:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.