Create Java 8 Stream from ArrayNode

前端 未结 2 1202
Happy的楠姐
Happy的楠姐 2021-02-12 06:04

Is it possible to create stream from com.fasterxml.jackson.databind.node.ArrayNode?
I tried:

ArrayNode files = (ArrayNode) json.get(\"files\")         


        
2条回答
  •  醉话见心
    2021-02-12 06:44

    An ArrayNode class provides random access: you can get size() and an element by index (using get(index)). This is all you need to create a good stream:

    Stream nodes = IntStream.range(0, files.size()).mapToObj(files::get);
    

    Note that this solution is better than using default spliterator (as suggested by other answerers) as it can split well and reports the size properly. Even if you don't care about parallel processing, some operations like toArray() will work more effectively as knowing the size in advance will help to allocate an array of proper size.

提交回复
热议问题