2

I was trying to pick a random element from a list of int and the list elements are created with range operator:

def date_range = 1..28
assert ('a'..'d').collect() == ['a','b','c','d'] // So this is instanceof List
assert ('a'..'d') == ['a','b','c','d'] // So this is instanceof List
def x1 = (1..28).collect().sort{new Random()}?.take(1)[0] // works
def x2 = date_range.collect().sort{new Random()}?.take(1)[0] // works
def x3 = date_range[0..27].sort{new Random()}?.take(1)[0] //works
def x4 = date_range.sort{new Random()}?.take(1)[0] // does not works

x4 yielding below Exception

Caught: java.lang.UnsupportedOperationException
java.lang.UnsupportedOperationException
    at listManipulation.run(listManipulation.groovy:21)

What is my mistake on x4?

Update:

My confusion is : if I define date_range as def date_range = 1..28 and check like: assert date_range instanceof List , than it passes. Why I should again convert it to list ?

Mahbub Rahman
  • 1,295
  • 1
  • 24
  • 44

1 Answers1

2

date_range is of type IntRange. No sure really why sort is unsupported on Range. But toSorted be used to achieve the same.

You should be able to call it using below:

def date_range = 1..28 
def x4 = date_range.toSorted {new Random()}?.take(1)[0]​
println x4

Also, convert range to an array or list before sort(this is what happened in case of x3) like below:

println date_range.toList().sort {new Random()}?.take(1)[0]
println date_range.toArray().sort {new Random()}?.take(1)[0]

Edit: Based on OP's comments.

date_range is immutable list.

In all your x1, x2, x3, you are creating a collection / list only(over immutable list) which becomes mutable and then able to do sort. Similarly above.

sort not allowed on immutable list.

Below works.

def mutableList = ['Groovy', 'Java', 'JRuby']
mutableList.sort()

However, once the list is immutable, then it does now allow and results UnsupportedOperation Exception.

def immutableList = ['Groovy', 'Java', 'JRuby'].asImmutable()
immutableList.sort()

Hope it is clear now.

Rao
  • 20,781
  • 11
  • 57
  • 77
  • Not every list might support `sort`. for ex see http://stackoverflow.com/questions/5755477/java-list-add-unsupportedoperationexception – Rao Mar 01 '17 at 05:43
  • Thank you very much for this valuable information and update ! So it means range operator (..) creates immutable list. – Mahbub Rahman Mar 01 '17 at 06:10