Chambers
-- -- --

How would I make this code cleaner with the use of Reduce

Anonymous in /c/coding_help

486
What I am trying to do is make this code work with the reduce function. I am trying to get it to work so that I can create an inception of code. <br><br> For context, what an inception in java is when you create a class, then have a field of that same Class. You then create a new instance of that Inception Class and in the constructor you have it take a parameter of that class then set it to the field.<br><br>```java<br>import java.util.List;<br>import java.util.stream.Collectors;<br><br>final class InitialInception {<br> private final List<Inception> inceptions;<br><br> public InitialInception(List<Inception> inceptions) {<br> this.inceptions = inceptions;<br> }<br><br> public List<Inception> getInceptions() {<br> return inceptions;<br> }<br>}<br><br>final class Inception {<br> private final Inception inception;<br><br> public Inception(Inception inception) {<br> this.inception = inception;<br> }<br><br> public Inception getInception() {<br> return inception;<br> }<br>}<br>```<br><br>Then here is the code that I am working on<br><br>```java<br>import java.util.stream.Collectors;<br>import java.util.stream.Stream;<br><br>public class Main {<br> public static Inception createInception(int depth) {<br> if(depth == 0) {<br> return new Inception(new InitialInception(List.of()));<br> } else {<br> return new Inception(new Inception(createInception(1)));<br> }<br> }<br><br> public static void main(String[] args) {<br> Inception inception = createInception(10);<br> Inception nestedInception = inception.getInception();<br> InitialInception initialInception = nestedInception.getInception().getInceptions().get(0);<br> }<br>}<br>```<br><br>I have been trying for a while now and I can't seem to wrap my head around this. I have tried using the reduce function but I get the Inception class which I don't want. I want to get the initialInception class.<br><br>Here is what I have tried:<br><br>```java<br> inception = Stream.generate(Inception::new)<br> .limit(depth)<br> .reduce(new InitialInception(List.of()),<br> (oldInception, newInception) -> {<br> oldInception.getInceptions().add(newInception);<br> return newInception;<br> },<br> (oldInception, newInception) -> newInception);<br>```<br><br>This doesn't seem to work. Any help would be great. Thank you.

Comments (10) 17539 👁️