Lambda Java 8, how to match a list that is the result of a filter

I have a catalog hierarchy of objects where each object has a name field.

class A {
    List<A> list;
    String name;
}

A{A{A{A...}AA},A{AAA},A{AAA}} // the depth is finite (~4)

I would like to provide a set of methods that return a list of child names (a.getName ()) of any parent element for the given name. So for level 1 I have

a.getAs().stream().map(a1 -> a1.getName()).collect(Collectors.toList());

Level 2 I already have problems with:

a1.getAs().stream().filter(a2 -> a2.getName() == name)

now I want to access As and match them with their names, but I don't know how

EDIT: , , . , node, . , . . , , .

, .

+4
2

:

public static List<String> getChildNames(A node, String... path) {
    Stream<A> s = node.getAs().stream();
    for(String name: path)
        s = s.filter(a -> a.getName().equals(name)).flatMap(a -> a.getAs().stream());
    return s.map(A::getName).collect(Collectors.toList());
}

A node , Map<String,A>, , List<A>. / , node.get(name1).get(name2). - , , .

public static List<String> getChildNames(A node, String... pathPatterns) {
    Stream<A> s = node.getAs().stream();
    for(String namePattern: pathPatterns) {
        Pattern compiledPattern = Pattern.compile(namePattern);
        s = s.filter( a -> compiledPattern.matcher(a.getName()).find())
             .flatMap(a -> a.getAs().stream());
    }
    return s.map(A::getName).collect(Collectors.toList());
}
+2

:

public List<A> getSubcategoriesByParentName(A category, String name) {
    return category.getSubcategories()
                   .stream()
                   .filter(subcategory -> subcategory.getName().equals(name))
                   .collect(Collectors.toList());
}

, flatMap:

category.getSubcategories().stream()
        .flatMap(s -> s.getSubcategories().stream())
        .filter(s -> s.getName().equals(name))
        .collect(Collectors.toList());

, , Stream API.

, , ( flatMap(s -> s.getSubcategories().stream()) ), .

+2

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


All Articles