寻找对象递归问题的最佳解决方案。以下是示例:
上课:
public class SomeObject {
private List<SomeObject> objects;
}
数据:
输入: SomeObject具有对象列表,列表中的每个Object都是SomeObject Type,并且在其中包含列表。 (本质上是递归的)
要求是将它们展平并将它们放在一个arraylist中。
flatten List应该包含所有SomeObject类型。
任何人都可以建议处理这种情况的最佳方式。谢谢!
答案 0 :(得分:0)
要进行递归,给定对象的方法需要:
getAllChildren()
public class Foo {
private String s;
private List<Foo> fooList = new ArrayList<>();
public Foo(String a) {
s = a;
}
public static void main(String[] args) {
Foo a = new Foo("a");
Foo b = new Foo("b");
Foo c = new Foo("c");
Foo d = new Foo("d");
Foo e = new Foo("e");
a.fooList.add(b);
b.fooList.add(c);
c.fooList.add(e);
a.fooList.add(d);
List<Foo> list = a.getAllChildren();
System.out.println(list);
}
private List<Foo> getAllChildren() {
List<Foo> l = fooList.stream().flatMap(elt -> elt.getAllChildren().stream())
.collect(Collectors.toList());
l.add(this);
return l;
}
@Override
public String toString() { return s; }
}
输入结构:
a-b-c-d
\ \
e f
输出列表:
[d, f, c, b, e, a]
答案 1 :(得分:0)
如果您不使用Java 8,您可以考虑这样做。
import java.util.ArrayList;
import java.util.List;
public class TestClass {
static List<SomeObject> flatList = new ArrayList<SomeObject>();
public static void flatten(SomeObject object) {
if (object != null ){
if( object.getObjects() != null && !object.getObjects().isEmpty()) {
for (SomeObject o : object.getObjects()) {
flatten(o);
flatList.add(object);
}
}
}
}
public static void main(String[] args) {
SomeObject o1 = new SomeObject("1");
SomeObject o2 = new SomeObject("2");
SomeObject o3 = new SomeObject("3");
SomeObject o4 = new SomeObject("4");
o1.addObject(o2);
o2.addObject(o3);
o3.addObject(o4);
flatten(o1);
for (SomeObject obj : flatList){
System.out.println(obj.getObjectName());
}
}
}
class SomeObject {
String objectName = "";
public SomeObject(String name) {
this.objectName = name;
}
private List<SomeObject> objects = new ArrayList<SomeObject>();
public List<SomeObject> getObjects() {
return objects;
}
public void setObjects(List<SomeObject> objects) {
this.objects = objects;
}
public void addObject(SomeObject o){
objects.add(o);
}
public String getObjectName() {
return objectName;
}
}