Issue
partnersName =["partner1","partner2"];
totalDates = ["2022-05-18","2022-05-19"];
both the lists store string only
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));
}
}
}
output =["partner1/2022-05-18","partner2/2022-05-18","partner1/2022-05-19","partner2/2022-05-19"];
but I want to reduce the line of code using stream. Anyone could help to get stream API code
Solution
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]
- The above uses nested streams to process each List.
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.
Answered By - WJS
Answer Checked By - Gilberto Lyons (JavaFixing Admin)