Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert Object and wrap to another with recursive field in java

For some reasons, I need a new object to wrap the data I get from other API.

The problem I faced was that no idea to handle recursive field from the original object.

Here is the sample code:

//original object
public class Resource{
    private String name;
    private String content;
    private Integer type;
    private List<Resource> children = new LinkedList();
    public void addChildrenResource(Resource children) {
        this.children.add(children);
    }
    //getters&setters...
}

//the object try to convert
public class Menu{
    private String name;
    private String url;
    private Integer type;
    private List<Menu> subMenu = new LinkedList();
    public void addChildrenResource(Menu subMenu) {
        this.children.add(subMenu);
    }
    //getters&setters...
}

The implementation I did that I have no idea to do with recursive field...
Here is my code..

List<Resource> resources = rpcService.getResources();

//Here I can't handle the subMenu or children part..
List<Menu> menus = resources.stream().map(r -> new Menu(r.getName(), 
r.getContent(), r.getType())).collect(Collectors.toList());  

The recursion may be many layers, so how can I convert it with recursive field?

Note: The Resource class is from another module so I can't change that, for naming problem I must convert it.
We don't have to solve it by Stream(), just find a way to figure it out.

like image 673
stephCurry Avatar asked Feb 15 '26 03:02

stephCurry


1 Answers

You need make a method and call this method recursively:

public static List<Menu> convert(List<Resource> resources) {
    return resources == null ? null :
            resources.stream()
                    .map(r -> new Menu(r.getName(), r.getContent(), r.getType(), convert(r.getChildren)))
                    .collect(Collectors.toList());
}
like image 189
xingbin Avatar answered Feb 17 '26 16:02

xingbin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!