Monday 15 February 2010

lambda - Java 8: Applying Stream map and filter in one go -



lambda - Java 8: Applying Stream map and filter in one go -

i writing parser file in java 8. file read using files.lines , returns sequential stream<string>.

each line mapped info object result this:

result parse(string _line) { // ... code here result _result = new result(). if (/* line not needed */) { homecoming null; } else { /* parse line result */ homecoming _result; } }

now can map each line in stream according result:

public stream<result> parsefile(path _file) { stream<string> _stream = files.lines(_file); stream<result> _resultstream = _stream.map(this::parse); }

however stream contains null values want remove:

parsefile(_file).filter(v -> v != null);

how can combine map/filter operation, know in parseline/_stream.map if result needed?

as pointed out in comments stream processed in 1 pass, there isn't need alter anything. it's worth utilize flatmap , allow parse homecoming stream:

stream<result> parse(string _line) { .. code here result _result = new result(). if (/* line not needed */) { homecoming stream.empty(); } else { /** parse line result */ homecoming stream.of(_result); } } public stream<result> parsefile(path _file) { homecoming files.lines(_file) .flatmap(this::parse); }

that way won't have null values in first place.

java lambda java-8 java-stream

No comments:

Post a Comment