简体   繁体   中英

java: convert object to list

I have the following classes:

public class UnidadOrganicaArbol {

protected long codigo;
@XmlElement(required = true)
protected String denominacion;
protected boolean tieneOficinaRegistro;
protected int prelacion;
@XmlElement(required = true)
protected UnidadesOrganicasArbol subunidades;

/*getters and setters*/
}

and also have

public class UnidadesOrganicasArbol
extends ListadoBase
{

protected List<UnidadOrganicaArbol> unidadOrganicaArbol;


public List<UnidadOrganicaArbol> getUnidadOrganicaArbol() {
    if (unidadOrganicaArbol == null) {
        unidadOrganicaArbol = new ArrayList<UnidadOrganicaArbol>();
    }
    return this.unidadOrganicaArbol;
}

As you can see, UnidadOrganicaArbol class hass an attribute subunidades which is an UnidadesOrganicasArbol class, which has a List<UnidadOrganicaArbol> attribute.

So, I have a UnidadOrganicaArbol class that contains a List<UnidadOrganicaArbol> attribute.

Let´s say that I have:

在此处输入图片说明

do you know any general algorithm to convert uoa1 (or any other UnidadOrganicaArbol object) and its children into a list where I can keep their ids and id parents of the children?

I have tried several ways but no success. Thanks in advance.

public List<UnidadOrganicaArbol> collectToList(UnidadOrganicaArbol arbol) {
    List<UnidadOrganicaArbol> result = new ArrayList<>();
    result.add(arbol);
    UnidadesOrganicasArbol children = arbol.getUnidadesOrganicasArbol();
    if (children != null) {
        for (UnidadOrganicaArbol child : children.getUnidadOrganicaArbol()) {
            result.addAll(collectToList(child));
        }
    }
    return result;
}

will yield you the list [\\, 7, 3, 6, 4, 5, 1, 2] for the above picture.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM