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
Answer from Eran on Stack OverflowEach 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
In your loop for(String word: strings) you overwrite your separatedByComma variable.
Using Java 8 you could do it in one line:
String addressID = addresses
.stream()
.map(a -> String.valueOf(a.addressId))
.collect(Collectors.joining(","));
for converting to comma seperated String use something like this:
String commaSeparatedStr = addresses
.stream()
.map(String::valueOf)
.collect(Collectors.joining(","));