Collections.sort 在 Java 中的 guava Lists.transform 函数之后对列表进行排序时抛出 UnsupportedOperationException?

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

我有一个列表,我使用 guava 的 Lists.transform 函数对其进行了转换。后来,当我尝试使用 Collections.sort() 对列表进行排序时,我得到了 UnsupportedOperationException

我的代码是这样的:

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;
    }

我不确定为什么会收到此错误。

Collections.sort 需要能够调用列表中的 set 并让它执行预期的操作。 transform 返回的列表不支持它的 set 方法(它是一个 "read only" 列表)。

一个简单的解决方法是创建一个新列表并对其进行排序

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

流是更好的解决方案