1
I’m trying to create a recursive method, which shows me all the cost centers children who do not have other children, for example:
If the father is the cost center 1, will return me the 3, 4 and 5. The 2 is not returned because he also has children.
What I’ve tried so far:
public class Teste {
public static List<CentroCusto> centroCustos = new ArrayList<>();
public static List<CentroCusto> centroCustos2 = new ArrayList<>();
public static void main(String[] args) {
build();
CentroCusto c1 = new CentroCusto();
c1.setId(1L);
buscarFilhos(c1);
System.out.println(centroCustos2);
}
private static CentroCusto buscarFilhos(CentroCusto ccu) {
if (!centroCustos.stream().map(CentroCusto::getCentroCustoPai).filter(Objects::nonNull).anyMatch(centroCusto -> centroCusto.getId().equals(ccu.getId()))) {
centroCustos2.add(ccu);
return ccu;
}
for (CentroCusto centroCusto : centroCustos) {
if (Objects.nonNull(centroCusto.getCentroCustoPai()) && centroCusto.getCentroCustoPai().getId().equals(ccu.getId())) {
return buscarFilhos(centroCusto);
}
}
return null;
}
private static void build() {
CentroCusto c1 = new CentroCusto();
c1.setId(1L);
CentroCusto c2 = new CentroCusto();
c2.setId(2L);
c2.setCentroCustoPai(c1);
CentroCusto c3 = new CentroCusto();
c3.setId(3L);
c3.setCentroCustoPai(c2);
CentroCusto c4 = new CentroCusto();
c4.setId(4L);
c4.setCentroCustoPai(c2);
CentroCusto c5 = new CentroCusto();
c5.setId(5L);
c5.setCentroCustoPai(c1);
CentroCusto c6 = new CentroCusto();
c6.setId(6L);
CentroCusto c7 = new CentroCusto();
c7.setId(7L);
c7.setCentroCustoPai(c6);
CentroCusto c8 = new CentroCusto();
c8.setId(8L);
c8.setCentroCustoPai(c7);
centroCustos.add(c1);
centroCustos.add(c2);
centroCustos.add(c3);
centroCustos.add(c4);
centroCustos.add(c5);
centroCustos.add(c6);
centroCustos.add(c7);
centroCustos.add(c8);
}
}
public class CentroCusto {
private Long id;
private CentroCusto centroCustoPai;
// Gettes e Setters
}
"If the father is the cost center 1, will return me the 3, 4 and 5" Cost center 2 is also child of 1, why should not appear?
– Gabriel
Because cost center 2 is parent of 3 and 4. I wanted to list only those who have no children.
– Diogo Zucchi