partnersName =["partner1","partner2"];
totalDates = ["2022-05-18","2022-05-19"];
两个列表仅存储字符串
下面的代码给出了我想要的输出
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));
}
}
}
输出 =["partner1/2022-05-18","partner2/2022-05-18","partner1/2022-05-19","partner2/2022-05-19"];
但是我想使用流来减少代码行。任何人都可以帮助获取流 API 代码
假设结果
[partner1/2022-05-18, partner1/2022-05-19, partner2/2022-05-18, partner2/2022-05-19]
就是你想要的:
List<String> result = partnersName.stream().<String>mapMulti((s, stringConsumer) -> totalDates.forEach(d -> stringConsumer.accept(s + "/" + d))).toList();
还有一种方法可以
List<String> result = partnersName.stream()
.flatMap(x -> totalDates.stream().map(y -> x.concat("/"+y)))
.collect(Collectors.toList());
//output: [partner1/2022-05-18, partner1/2022-05-19, partner2/2022-05-18, partner2/2022-05-19]
这是一种方法。
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);
打印
[partner1/2022-05-18, partner1/2022-05-19, partner2/2022-05-18, partner2/2022-05
-19]
String.join
- 采用分隔符和可变数量的参数并将它们连接起来,由分隔符分隔。flatMap
将嵌套流展平为一个以转换为列表。