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
...
}
split() method: String[] tokens = str. split(",");
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.
A List of string can be converted to a comma separated string using built in string. Join extension method. string. Join("," , list);
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 String
s 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
In your loop for(String word: strings)
you overwrite your separatedByComma
variable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With