get a comma separated string using java stream
Asked Answered
H

3

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
    ...
}
Haig answered 14/11, 2018 at 8:20 Comment(0)
M
34

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
Mail answered 14/11, 2018 at 8:25 Comment(1)
Thank you very much, your solution produces exactly what I needed.Haig
P
4

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

Paulpaula answered 14/11, 2018 at 8:23 Comment(3)
I think you are right, could you let me know how to fix it? sorry I am new to java stream...Haig
If you want to filter occList and allow only those which getOccSCd is in list of string I can give you code sample.Paulpaula
thanks so much for your quick answer as well. It was very helpful!Haig
G
1

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

Glucose answered 1/9, 2023 at 12:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.