Given the following lists of strings:
partnersName = ["partner1","partner2"];
totalDates = ["2022-05-18","2022-05-19"];
Here is the following code which gives output that I want:
for (int i = 0; i < partnersName.size(); i++) {
if (totalDates.isEmpty()) {
totalDates.add(partnersName.get(i));
} else {
for (int j = 0; j < totalDates.size(); j++) {
totalDates.set(j, partnersName.get(i) +"/" +totalDates.get(j));
}
}
}
Desired output:
output = ["partner1/2022-05-18","partner2/2022-05-18","partner1/2022-05-19","partner2/2022-05-19"];
I want to reduce the line of code using the Java stream API. Could anyone help to get stream API code?
Here is one way.
List<String> partnerName = List.of("partner1","partner2");
List<String> totalDates = List.of("2022-05-18","2022-05-19");
List<String> result = partnerName.stream()
.flatMap(name -> totalDates.stream()
.map(date->String.join("/", name, date)))
.toList();
System.out.println(result);
prints
[partner1/2022-05-18, partner1/2022-05-19, partner2/2022-05-18, partner2/2022-05
-19]
String.join
- takes a delimiter and a variable number of arguments and concatenates them, separated by the delimiter.flatMap
flattens the nested streams into one for conversion to a list.