Filter java 8 nested object

I have these classes

class LivingOrganism
{
    List<Domain> listOfDomain;
}

class Domain
{
    List<Species> listOfSpecies;
}

class Species
{
    List<Color> listOfColor;
}

class Color
{
    String color;
}

From top to bottom, it will not have duplicate entries until it reaches color. Thus, some species, even if they are in a different domain, may have the same color. And one species may have a different color.

Given the parent LivingOrganism, I want to filter listOfDomain with a specific color.

I did this in a classic nested loop, but with 4 sockets, the code doesn't look very pretty. I tried using java 8 flatmap and filter to get more elegant code, but I spent hours without success.

I even made a poorly drawn graph in MSPaint

Say I want to get List<Species>one that can be blue or List<Domain>with all Speciesthat can be blue. How can I continue?

Any help would be appreciated

+4
2

.

List<Domain> result = livingOrganism.listOfDomain.stream()
    .filter(d -> d.listOfSpecies.stream()
        .flatMap(s -> s.listOfColor.stream())
        .anyMatch(c -> c.equals("blue")))
    .collect(Collectors.toList());
+3

Color btw enum, , . listOfDomains, listOfSpecies listOfColors ( s ).

 String colorOfIntereset = "red";

 LivingOrganism one = new LivingOrganism...
 List<Domain> domains = one.getListOfDomain()
            .stream()
            .filter(d -> {
                return d.getListOfSpecies()
                        .stream()
                        .flatMap(s -> s.getListOfColor().stream())
                        .anyMatch(c -> c.getColor().equals(colorOfIntereset));
            })
            .collect(Collectors.toList());
+3

Source: https://habr.com/ru/post/1679494/


All Articles