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.
In Java 8 you can use String.join() like following:
Collection<String> elements = ....;
String result = String.join(", ", elements);
With Java 8, you can use streams with joiners.
Collection<String> strings;
...
String commaDelimited = strings.stream().collect(Collectors.joining(","));
// use strings.parallelStream() instead, if you think
// there are gains to be had by doing fork/join