https://kotlinlang.org logo
#getting-started
Title
# getting-started
d

Daniele B

08/08/2020, 9:55 PM
Copy code
mylist.sortedBy{it.quantity}.map {
	NewElement(
		position = (how to retrieve the index of the element in the sorted list?)
		name = it.name,
		quantity = it.quantity
	)
}
is there any way to retrieve the index of the element?
n

nanodeath

08/08/2020, 9:57 PM
.mapIndexed
also I'd lead with
.asSequence()
and end with
.toList()
to avoid allocating more lists than you need.
👍 1
d

Daniele B

08/08/2020, 10:01 PM
great! thanks
@nanodeath do you mean like this?
Copy code
list.asSequence().sortedBy{it.quantity}.toList().mapIndexed { index, elem ->
	NewElement(
		position = index
		name = elem.name,
		quantity = elem.quantity
	)
}
n

nanodeath

08/08/2020, 10:08 PM
toList()
should usually be at the end, otherwise you got it
d

Daniele B

08/08/2020, 10:08 PM
can you explain better what are the advantages of using
asSequence()
and then
toList()
?
because actually what I am doing here, it is to create a new list of a NewElement type
n

nanodeath

08/08/2020, 10:09 PM
so if you say
foo.map {}.map {}.reduce{}
or whatever, every step generates a new list. if you say
asSequence().map {}.map{}.map{}.reduce{}.toList()
(or
toSet()
), it minimizes the use of intermediate collections by doing fancy lazy iterator stuff
the general rule I follow is if you're doing more than one operation (e.g. map or reduce) in a chain, use a sequence
(granted it's a bit of a moot point in this particular case because
sortedBy
almost certainly creates a list internally, but...things like
map
don't)
👍 1
d

Daniele B

08/08/2020, 10:11 PM
Ok, I see, thanks for the explanation
n

nanodeath

08/08/2020, 10:11 PM
Sequences are lazy the same way Streams are -- they don't "do" anything unless there's a terminal node (like toList or toSet) to pull the values through
👍
2 Views