How do I turn a Java Enumeration into a Stream?

前端 未结 5 2161
攒了一身酷
攒了一身酷 2021-02-01 00:11

I have a third party library that gives me an Enumeration. I want to work with that enumeration lazily as a Java 8 Stream, calling thing

5条回答
  •  旧时难觅i
    2021-02-01 00:56

    Why not using vanilla Java :

    Collections.list(enumeration).stream()...
    

    However as mentionned by @MicahZoltu, the number of items in the enumeration has to be taken into account, as Collections.list will first iterate over the enumeration to copy the elements in an ArrayList. From there the regular stream method can be used. While this is usual for many collection stream operations, if the enumeration is too big (like infinite), this can cause problem because the enumeration has to be transformed in a list then the other approaches described here should be used instead.

提交回复
热议问题