Create Java 8 Stream from ArrayNode

前端 未结 2 1203
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 07:12

    ArrayNode#elements returns an Iterator over it's elements you can use that to create a Stream (by leveraging StreamSupport). StreamSupport requires a Spliterator and to create a Spliterator from an Iterator you can use the Spliterators class.

      ArrayNode files = (ArrayNode) json.get("files");
      Stream  elementStream = StreamSupport.stream(Spliterators
                      .spliteratorUnknownSize(files.elements(),
                            Spliterator.ORDERED),false);
    

    cyclops-streams has a StreamUtils class has a static method that makes this a bit cleaner (I am the author).

     ArrayNode files = (ArrayNode) json.get("files");
     Stream  elementStream = StreamUtils.stream(files.elements());
    

    Taking into account @JB Nizet's answer that ArrayNode is an iterable with StreamUtils you can pass in the ArrayNode and get the Stream back directly.

    Stream  elementStream = StreamUtils.stream((ArrayNode) json.get("files"));
    

提交回复
热议问题