gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 03:04:21 30 4
gpt4 key购买 nike

我有一个列表,我使用 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 方法(它是一个“只读”列表)。

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

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

流是更好的解决方案

关于java - Collections.sort 在 Java 中 Guava 的 Lists.transform 函数之后对列表进行排序时抛出 UnsupportedOperationException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53065894/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com