Java 8 stream - reference to the source stream object after a flat map

I currently have a code.

Method - parseGreeting ()

    public GetGreetingNmsObjects parseGreeting(String greetingType, GetGreetingNmsResponse xmlFromNms) {

    GetGreetingNmsObjects objectFound = null;
    List<GetGreetingNmsObjects> objList = xmlFromNms.getObject();
    for (GetGreetingNmsObjects obj : objList) {

        List<Attribute> attrs = obj.getAttributes();
        Optional<Boolean> found = attrs.stream()
                                 .filter(a -> a.name.equals(GREETING_TYPE))
                                 .map(a -> a.value.equals(greetingType))
                                 .findAny();

        if(found.get()) {
            objectFound = obj;
            break;
        }

    return objectFound;
}

GetGreetingNmsObjects.java

public class GetGreetingNmsObjects {
    List<Attribute> attributeList;

    public List<Attribute> getAttributes() {
        return attributeList;
    } 
}

In the above method, is there a way to avoid the for loop, and if the operator and handle to the threads themselves?

I tried using "flatmap" and getting the stream for "attributesList", but as soon as a match was found, I could not get a reference to the GetGreetingNmsObjects object.

GetGreetingNmsObjects objectFound = objList.stream()
                                   .flatMap(grt -> grt.getAttributes())
                                   .filter(a -> a.name.equals(GREETING_TYPE))
                                   .map(a -> a.value.equals(greetingType))
                                   ????
+4
source share
1 answer

The source code contains a logical error:

Optional<Boolean> found = …
                         .map(a -> a.value.equals(greetingType))
                         .findAny();

This will return the result of an arbitrary comparison in a consistent context, probably the result of the first element.

, , - , ,

boolean found = …
               .anyMatch(a -> a.value.equals(greetingType));

, :

return xmlFromNms.getObject().stream()
    .filter(obj -> obj.getAttributes().stream()
                      .filter(  a -> a.name.equals(GREETING_TYPE))
                      .anyMatch(a -> a.value.equals(greetingType)))
    .findFirst().orElse(null);
+11

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


All Articles