Search code examples
javalambdajava-8java-streamnio

Java 8: Stream, NIO and Lambda


I have a file that contains multiple lines. Each line can be converted into JSONObject.

Example lines,

{"name": "a", "age": 28}
{"name": "b", "age": 20}
{"name": "c", "age": 30}

I am reading this file using new IO

Files.lines(path)

I want to use stream and convert each line to JSONObject like,

JSONObject obj = new JSONObject(line);

I am not getting how to do using stream and lambda. Is there any way?


Solution

  • use Stream#map, example:

    List<JSONObject> result;
    try (Stream<String> stream = Files.lines(Paths.get(fileName))) {    
            result = stream.map(line -> new JSONObject(line)) // or map(JSONObject::new)
                           .collect(Collectors.toList());       
    } catch (IOException e) { /* handle exception */}