id like to also ask how to rewrite this in more functional style ``` val maxSize = BookDao.RECENTS_S...
u
id like to also ask how to rewrite this in more functional style
Copy code
val maxSize = BookDao.RECENTS_SIZE
val all = mutableListOf<RealmObject>()
all.addAll(it.findAllRecentSearchedBooks().run { if (this.size > maxSize) subList(0, maxSize) else this })
all.addAll(it.findAllRecentSearchedAuthors().run { if (this.size > maxSize) subList(0, maxSize) else this })

all.sortByDescending {
	when (it) {
	        is RecentlySearchedBook -> it.timestamp
	        is RecentlySearchedAuthor -> it.timestamp
	        else -> error("Unknown type")
        }
}

val allUnmamaged = mutableListOf<SearchItem>()
for (i in 0 until Math.min(all.size, maxSize)) {
	allUnmamaged.add(it.unmanaged(all[i]) as SearchItem)
}

allUnmamaged
d
Copy code
val all = it.findAllRecentSearchedBooks().take(maxSize) + it.findAllRecentSearchedAuthors.take(maxSize)
          .sortedByDecending {...}
For a start.
and then you can do
Copy code
val allUnmanaged = all.map { item -> it.unmanaged(item) as SearchItem }
u
sweet
is there a way to not break the chain, i.e. sort returns unit
d
sorted
returns sorted copy,
sort
sorts in place
u
i see, thanks
d
So if you want to avoid all the intermediate collections, use sequences
u
arent sequences from coorutines?
d
But if that is needed depends on the size of your collections
No
Standard library
u
ill look into it, thnx
like an iterable, but lazy. So if you
map
twice with a sequence, your collection is only traversed once
u
you mean instantiated?
d
No. If you have a
List
and you call
map
on it, a new
List
of the same length will be allocated and the result will be stored in it.
So if you map twice, you will get two lists
With a Sequence you still get new objects allocated, but they only store the source collection and the operation
u
yea, thats what I meant
d
And the operations are all applied in one go if you convert to a normal collection again in the end
Similar to a Stream in the JDK
u
so its like inline imperative collection processing with functional api?
d
Sorry, I have no idea what you mean by that 😄
u
like, gc aware functional style
or whatever :d
d
I guess you could call it that. Like I said, depends on how big your collections are
For small collections the non-lazy approach is faster
You gotta benchmark for your specific use case if you have a problem
u
k, thanks