java - Can I flatten multi depth self-referencing entities? -


i have entity self-references.

public class category {      private list<category> children; } 

with given list of categories, how can flatten them all?

c11     c21         c31         c32     c22 c12 

i want list of

c1 c21 c31 c32 c22 c12 

i tried.

public static <t extends baseentity & selfreferencing<t>> void flatten(         final t parent, final function<t, stream<t>> function,         final consumer<t> consumer) {     function.apply(parent).foreach(child -> {         consumer.accept(child);         flatten(child, function, consumer);     }); } 

i took code , improved little.

public static <t extends baseentity & selfreferencing<t>> list<t> flatten(         final t parent, final function<t, stream<t>> function) {     list<t> res = new arraylist<>();     res.add(parent);     res.addall(function.apply(parent).flatmap(child -> {         flatten(child, function).stream();     }).collect(collectors.tolist()));     return result; } 

i don't see why need consumer , removed it. there conversion stream , back.


Comments

Popular posts from this blog

asynchronous - C# WinSCP .NET assembly: How to upload multiple files asynchronously -

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -