寻找对象递归问题的最佳解决方案。下面是示例:
类:
public class SomeObject {
private List<SomeObject> objects;
}数据:
输入: SomeObject有对象列表,列表中的每个对象都是SomeObject类型,并且在它们内部有List。(本质是递归的)
要求是将它们展平,并将它们放入单个数组列表中。
展平列表应该包含所有的SomeObject类型。
有谁能建议一下处理这种情况最好的方法是什么?谢谢!
发布于 2018-06-07 03:51:06
如果您使用的不是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;
}
}发布于 2018-06-07 03:14:45
要进行递归,给定对象的方法需要:
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]https://stackoverflow.com/questions/50727663
复制相似问题