16

I have the following code using java Stream.

I am trying the get the function to build a string of value: "a,b" in this case. however, the output (separatedByComma in this case) is always "b".

Could somebody shed some light please?

@Test
public void testJoin() {
    List<MOccS> occList = new ArrayList<> (  );
    MOccS mOccS = new MOccS ();
    mOccS.setOccSCd ( "1" );
    mOccS.setOccSNm ( "a" );
    occList.add ( mOccS );

    MOccS mOccS2 = new MOccS ();
    mOccS2.setOccSCd ( "2" );
    mOccS2.setOccSNm ( "b" );
    occList.add ( mOccS2 );


    List<String> strings = new ArrayList<> (  );
    strings.add ( "1" );
    strings.add ( "2" );

    String separatedByComma = "";
    for(String word: strings) {
        separatedByComma = occList.stream ()
                                  .filter ( occ -> word.equalsIgnoreCase ( occ.getOccSCd () ) )         
                                  .map ( occ -> occ.getOccSNm () )
                                  .collect ( Collectors.joining ( "," ) );
     }

     System.out.println (separatedByComma);
}


class MOccS{
    String occSCd;
    String occSNm;
    ...
    getter/setter
    ...
}

3 Answers 3

35

Each iteration of your for loop overwrites the value of separatedByComma. The first iteration assigns the String "a" to it, and the second replaces it with "b".

You should Stream over the elements of the strings List in order to join the Strings that match each of them into a single output String:

String separatedByComma = 
    strings.stream()
           .flatMap(word -> occList.stream()
                                   .filter(occ -> word.equalsIgnoreCase (occ.getOccSCd()))
                                   .map (occ -> occ.getOccSNm()))
           .collect(Collectors.joining (","));

Output:

a,b
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much, your solution produces exactly what I needed.
3

In your loop for(String word: strings) you overwrite your separatedByComma variable.

3 Comments

I think you are right, could you let me know how to fix it? sorry I am new to java stream...
If you want to filter occList and allow only those which getOccSCd is in list of string I can give you code sample.
thanks so much for your quick answer as well. It was very helpful!
2

You can also use String.join(",", strings)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.