Have a SortedSet where I need a specific slice of records based on a specific element in the list.
Example:
In the code below, challengeDTO.members is a SortedSet (TreeSet implementation)
I know the location of one member
def memberRank = challengeDTO.members.findIndexOf { it.member.id == membership?.id} + 1
If the memberRank is 66, I want to get a slice of members 60 through 70 ranks.
challengeDTO.members[60..69] won’t work because it’s a set
Ideas? Suggestions?
Member implementation:
class ChallengeMemberDTO implements Comparable<ChallengeMemberDTO> {
ChallengeMember member
Integer total
String name
String teamName
int compareTo(ChallengeMemberDTO t) {
if (total == t.total) { // the sortedset will remove duplicates based on same total, which is not desireable
return name.compareTo(t.name)
}
else {
return t.total.compareTo(total)
}
}
}
Try:
Under the covers the Groovy
as Listtype conversion creates an instance ofArrayListand callsaddAll, passing your SortedSet. As per thejava.util.ListJavaDocaddAll“appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection’s iterator”. In thejava.util.SortedSetJavaDoc it states that “the set’s iterator will traverse the set in ascending element order.”So the order of the list will match the order of the SortedSet.
If you’re interested, you can take a look at the method in the Groovy source code:
org.codehaus.groovy.runtime.DefaultGroovyMethods.asList(Collection<T> self)EDIT:
For the sake completeness, in Java you could do the following. It’s just what the Groovy code above does under the covers: