zaozaoer
zaozaoer

Reputation: 387

get a comma separated string using java stream

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
    ...
}

Upvotes: 16

Views: 28039

Answers (3)

Pribic Rubik
Pribic Rubik

Reputation: 31

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

Upvotes: 1

talex
talex

Reputation: 20455

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

Upvotes: 3

Eran
Eran

Reputation: 393791

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

Upvotes: 34

Related Questions