Last active
December 6, 2021 02:19
-
-
Save wplong11/57f1dcdac96270bc919f39ebc8101988 to your computer and use it in GitHub Desktop.
Java AbstractSpliterator vs Kotlin Sequence
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class JsonObjectSpliterator<T>( | |
| private val mapper: ObjectMapper, | |
| private val inputStream: InputStream, | |
| private val clazz: Class<T> | |
| ) : Spliterators.AbstractSpliterator<T>(Long.MAX_VALUE, NONNULL or IMMUTABLE) { | |
| private val parser: JsonParser by lazy { | |
| mapper.createParser(inputStream.reader(Charsets.UTF_8)).also { | |
| check(it.nextToken() === JsonToken.START_ARRAY) { "Expected content to be an array" } | |
| } | |
| } | |
| override fun tryAdvance(action: Consumer<in T>): Boolean { | |
| if (parser.nextToken() === JsonToken.END_ARRAY) return false | |
| action.accept(mapper.readValue(parser, clazz)) | |
| return true | |
| } | |
| } | |
| fun <T> InputStream.toObjectStream(clazz: Class<T>): Stream<T> { | |
| return StreamSupport.stream(JsonObjectSpliterator(ObjectMapper(), this, clazz), false) | |
| } | |
| fun test2() { | |
| inputStream.toObjectStream(Product::class.java).forEach { product -> | |
| logger.debug { product } | |
| } | |
| } | |
| //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// | |
| fun <T> InputStream.toObjectSequence(clazz: Class<T>): Sequence<T> { | |
| val mapper = ObjectMapper() | |
| val parser: JsonParser = mapper.createParser(this.reader(Charsets.UTF_8)) | |
| check(parser.nextToken() === JsonToken.START_ARRAY) { "Expected content to be an array" } | |
| return sequence { | |
| while (parser.nextToken() !== JsonToken.END_ARRAY) { | |
| yield(mapper.readValue(parser, clazz)) | |
| } | |
| } | |
| } | |
| fun test2() { | |
| inputStream.toObjectSequence(Product::class.java).forEach { product -> | |
| logger.debug { product } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment