Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
    ...
}
like image 633
zaozaoer Avatar asked Nov 14 '18 08:11

zaozaoer


People also ask

How do you read a comma separated string in Java?

split() method: String[] tokens = str. split(",");

How do you collect stream strings?

We can use Stream collect() function to perform a mutable reduction operation and concatenate the list elements. The supplier function is returning a new StringBuilder object in every call. The accumulator function is appending the list string element to the StringBuilder instance.

How do you convert a list to a comma separated string?

A List of string can be converted to a comma separated string using built in string. Join extension method. string. Join("," , list);


2 Answers

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
like image 133
Eran Avatar answered Oct 25 '22 02:10

Eran


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

like image 21
talex Avatar answered Oct 25 '22 01:10

talex