sách gpt4 ai đã đi

java - 如何遍历包含相同类型列表的 List

In lại 作者:塔克拉玛干 更新时间:2023-11-02 19:12:56 hai mươi bốn 4
mua khóa gpt4 Nike

Tôi có một cái Danh sáchcủa Kiểu具有以下结构的类:

class Type {
private String name;
private String level;
private List types;
}

Đây là của tôi AnotherType结果我想建立。

class AnotherType {
private String name;
private List types;
}

我正在 build List来自请求的对象 Giao diện người dùng :

{
"types": [
{
"level": "1",
"name": "Name1"
},
{
"level": "2",
"name": "Name2",
"types": [
{
"level": "2.1",
"title": "Name2.1",
"types": [
{
"level": "2.1.1",
"name": "Name2.1.1"
},
{
"level": "2.1.2",
"title": "Name2.1.2"
}
]
}
]
},
{
"level": "3",
"name": "Name3",
"types": [
{
"level": "3.1",
"name": "Name3.1",
"types": [
{
"level": "3.1.1",
"name": "Name3.1.1"
},
{
"level": "3.1.2",
"name": "Name3.1.2"
}
]
}
]
}
]
}

您可以看到每个 các loại可以在那里或可以vô giá trị .

不知道能走多远。

我的问题是我如何递归(或迭代)遍历这个 List并构建List ?

Cảm ơn trước.

1 Câu trả lời

首先,在您的类中添加 getter/setter 以访问和修改您的私有(private)字段。然后你可以使用下面的方法递归转换KiểuĐẾN AnotherType .

public AnotherType toAnotherType(Type type) {

AnotherType anotherType = new AnotherType();
anotherType.setName(type.getName());

if (type.getTypes() != null && !type.getTypes().isEmpty()) {

List lAnotherTypes = new ArrayList<>();

for(Type innerType : type.getTypes()) {
AnotherType innerAnotherType = toAnotherType(innerType);
lAnotherTypes.add(innerAnotherType);
}
anotherType.setTypes(lAnotherTypes);
}

return anotherType;
}

然后有了这个方法你就可以在List上遍历一次并调用toAnotherType每个 Kiểu 的方法:

List allAnotherTypes = new ArrayList<>();

for (Type type : types) {
AnotherType anotherType = toAnotherType(type);
allAnotherTypes.add(anotherType);
}

Hy vọng thông tin này có ích với bạn.

关于java - 如何遍历包含相同类型列表的 List,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41177270/

hai mươi bốn 4 0
Giấy chứng nhận ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com