```mylist.sortedBy{it.quantity}.map { NewElement(...
# getting-started
d
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
.mapIndexed
also I'd lead with
.asSequence()
and end with
.toList()
to avoid allocating more lists than you need.
👍 1
d
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
toList()
should usually be at the end, otherwise you got it
d
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
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
Ok, I see, thanks for the explanation
n
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
👍