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", "...

问题:

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?


回答1:

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 */}
  • 发表于 2018-12-28 01:02
  • 阅读 ( 220 )
  • 分类:网络文章

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除