gpt4 book ai didi

java - 如何在Java中将列表的列表转换为二维数组

转载 作者:行者123 更新时间:2023-12-02 10:01:37 25 4
gpt4 key购买 nike

我想出了以下解决方案,不确定是否可以使用其他方法删除 Type:safety 警告。

BiFunction<List<List<T>>, Class<T>,T[][]> toArray = (list,type) ->
{
T a[][] = (T[][]) Array.newInstance(type,
list.size(), list.get(0).size());
IntStream.range(0, a.length)
.forEach(i -> {
a[i]=(T[]) list.get(i).toArray();
});
return a;
};

此外,如果可以通过一个管道来改进这一点,我将不胜感激该解决方案。

最佳答案

我有两个建议,将 List 转换为 List 迭代 List of List 并将每个元素作为 T[] 添加到新列表中。

仅使用 Array.newInstance 创建辅助对象并添加 @SuppressWarnings 注解

    @SuppressWarnings("unchecked")
public static <T> T[][] toArray(List<List<T>> list, Class<T> type) {

T aux[] = (T[]) Array.newInstance(type, 0);
T auxBi[][] = (T[][]) Array.newInstance(type, 0, 0);

List<T[]> newList = new ArrayList<>();
list.forEach(e -> newList.add(e.toArray(aux)));

T[][] newBi = newList.toArray(auxBi);

return newBi;
}

添加辅助参数作为参数而不是类型

public static <T> T[][] toArray(List<List<T>> list, T aux[], T auxBi[][]) {

List<T[]> newList = new ArrayList<>();
list.forEach(e -> newList.add(e.toArray(aux)));

T[][] newBi = newList.toArray(auxBi);

return newBi;

}

关于java - 如何在Java中将列表的列表转换为二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55578832/

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