How to find the value indices in a collection

Referring to this question: How to subtract dates from each other

In Groovy, I have a script that spills out the 5 largest values โ€‹โ€‹from a collection of text files. How can I find out what are the indices of these values?

0
source share
2 answers

If you have a list of things, for example:

def list = [ 'c', 'a', 'b' ] 

One way to find out the source index is to use transpose() to combine this list into a counter, then sort the new list, then you will have a sorted list with the source index as a secondary element

t

 [list,0..<list.size()].transpose().sort { it[0] }.each { item, index -> println "$item (was at position $index)" } 

To break it down

 [list,0..<list.size()] 

gives (effectively) a new list [ [ 'c', 'a', 'b' ], [ 0, 1, 2 ] ]

calling transpose() on this gives us: [ [ 'c', 0 ], [ 'a', 1 ], [ 'b', 2 ] ]

Then we sort the list based on the first element in each element (letters from our original list) with sort { it[0] }

And then iterate over each of them, printing out our sorted element and its original index location

0
source

If the values โ€‹โ€‹are unique, you can simply use the indexof method compared to the original list. For example, if you have a list:

 def list = [4, 8, 0, 2, 9, 5, 7, 3, 6, 1] 

And you know how to get the 5 biggest values:

 def maxVals = list.sort(false, {-it}).take 5 // This list will be [9, 8, 7, 6, 5] 

Then you can:

 def indexes = maxVals.collect { list.indexOf it } println indexes 

And he will print:

 [4, 1, 6, 8, 5] 
0
source

Source: https://habr.com/ru/post/1380748/


All Articles