wesvin
wesvin

Reputation: 45

Java streams, filter based on condition in an object, set value to a string and a an array

I am new to java streams. Trying to set 2 values based on a condition inside Java streams. I tried using flatmap. Probably doing something wrong.

The working code which i want to convert to streams is :

String NUME_AGENT = "";
for(int i = 0; i < reportInputOptionsExtsElemAgent.length; i++) {
    if(reportInputOptionsExtsElemAgent[i].getKey().equalsIgnoreCase(loadAGENT_ID)){
        NUME_AGENT = reportInputOptionsExtsElemAgent[i].getValue();
        reportInputOptionsExtsElemAgent = 
            new ReportInputOptionsExt[] {
                new ReportInputOptionsExt(loadAGENT_ID,
                    reportInputOptionsExtsElemAgent[i].getValue())
            };
    }
}

My attempt :

String NUME_AGENT =
        Arrays.stream(reportInputOptionsExtsElemAgent) // not sure about this
            .flatMap(agent -> agent.stream) // not sure about this
            .filter(rgp-> rgp.getKey().equalsIgnoreCase(loadAGENT_ID))
            .findFirst()
            .map(rgp->rgp.getValue())
            .orElse("");

Upvotes: 1

Views: 2433

Answers (2)

Learner
Learner

Reputation: 21405

You can create the object inside the map method:

ReportInputOptionsExt ext  = Arrays.stream(reportInputOptionsExtsElemAgent)
                                        .filter(rgp-> rgp.getKey().equalsIgnoreCase(loadAGENT_ID))
                                        .findFirst()
                                        .map(rgp->new ReportInputOptionsExt(loadAGENT_ID, rgp.getValue()))
                                        .orElse(null);  

Upvotes: 1

Ousmane D.
Ousmane D.

Reputation: 56433

you don't need the flatMap:

 String NUME_AGENT  = Arrays.stream(reportInputOptionsExtsElemAgent)
              //.flatMap(agent -> agent.stream) <---------- you don't need this
              .filter(rgp-> rgp.getKey().equalsIgnoreCase(loadAGENT_ID))
              .findFirst()
              .map(rgp->rgp.getValue())
              .orElse("");

and then:

reportInputOptionsExtsElemAgent = new ReportInputOptionsExt[]{new ReportInputOptionsExt(loadAGENT_ID, NUME_AGENT  )};

Upvotes: 4

Related Questions