Collections.sort throws UnsupportedOperationException while sorting a List after guava's Lists.transform function in Java?

Viewed 1795

I have a list which I transform using guava's Lists.transform function. Later, when I try to sort the list using Collections.sort(), I get an UnsupportedOperationException.

My code look's like this:

private List<SelectItemInfo> convertToSelectItemList(
        final List<String> dataOwnersOfActiveQualifiers)
    {

        final List<SelectItemInfo> dataOwnersSelectItemList = transform(dataOwnersOfActiveQualifiers,
            new Function<String, SelectItemInfo>()
            {
                public SelectItemInfo apply(final String input)
                {
                    final Employee employee = getLdapQuery().findEmployeesByIdOrLogin(input);
                    return new SelectItemInfo(input, employee.toStringNameSurname());
                }
            });
        Collections.sort(dataOwnersSelectItemList, this.comparator);
        return dataOwnersSelectItemList;
    }

I am not sure why I am getting this error.

1 Answers

Collections.sort needs to be able to call set on the list and have it do the expected thing. The list returned by transform doesn't support its set method (it's a "read only" list).

An easy fix is to create a new list and sort that

List<SelectItemInfo> sortedCopy = new ArrayList(dataOwnersSelectItemList);
Collections.sort(sortedCopy, this.comparator);
// use sortedCopy

Streams are a better solution

Related