我有一个 List
的 Type
具有以下结构的类:
class Type {
private String name;
private String level;
private List<Type> types;
}
这是我的 AnotherType
结果我想建立。
class AnotherType {
private String name;
private List<AnotherType> types;
}
我正在 build List<Type>
来自请求的对象 UI
:
{
"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"
}
]
}
]
}
]
}
您可以看到每个 types
可以在那里或可以null
.
不知道能走多远。
我的问题是我如何递归(或迭代)遍历这个 List<Type>
并构建List<AnotherType>
?
提前致谢。
最佳答案
首先,在您的类中添加 getter/setter 以访问和修改您的私有(private)字段。然后你可以使用下面的方法递归转换Type
至 AnotherType
.
public AnotherType toAnotherType(Type type) {
AnotherType anotherType = new AnotherType();
anotherType.setName(type.getName());
if (type.getTypes() != null && !type.getTypes().isEmpty()) {
List<AnotherType> lAnotherTypes = new ArrayList<>();
for(Type innerType : type.getTypes()) {
AnotherType innerAnotherType = toAnotherType(innerType);
lAnotherTypes.add(innerAnotherType);
}
anotherType.setTypes(lAnotherTypes);
}
return anotherType;
}
然后有了这个方法你就可以在List<Type>
上遍历一次并调用toAnotherType
每个 Type
的方法:
List<AnotherType> allAnotherTypes = new ArrayList<>();
for (Type type : types) {
AnotherType anotherType = toAnotherType(type);
allAnotherTypes.add(anotherType);
}
希望这对您有所帮助。
关于java - 如何遍历包含相同类型列表的 List<Type>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41177270/