我的意见是:
List<Map<String, String>> = [{1=a, 2=b, 3=c},
{1=d, 2=e, 3=f}]
List<String> = [x, y, z]
预期输出为:
[
{1=a, 2=b, 3=c, 4=x},
{1=a, 2=b, 3=c, 4=y},
{1=a, 2=b, 3=c, 4=z},
{1=d, 2=e, 3=f, 4=x},
{1=d, 2=e, 3=f, 4=y},
{1=d, 2=e, 3=f, 4=z}
]
我的代码:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class ExplodeData {
public static void main(String[] args) {
List<Map<String, String>> listOfMap = List.of(
new HashMap<>(Map.of("1", "a", "2", "b", "3", "c")),
new HashMap<>(Map.of("1", "d", "2", "e", "3", "f"))
);
List<String> stringList = new ArrayList<>();
stringList.add("x");
stringList.add("y");
stringList.add("z");
listOfMap.forEach(System.out::println);
System.out.println(stringList + "\n\n");
List<Map<String, String>> result = new ArrayList<>();
for (Map<String, String> eachMap: listOfMap) {
for (String eachString: stringList) {
Map<String, String> newEntry = new HashMap<>();
newEntry.putAll(eachMap);
newEntry.put("4", eachString);
result.add(newEntry);
}
}
System.out.println("Expected Result using for loops");
result.forEach(System.out::println);
List<Map<String, String>> result2 = stringList
.stream()
.flatMap(each -> listOfMap.stream().peek(entry -> entry.put("4", each)))
.collect(Collectors.toList());
System.out.println("\n\nResult using streams");
result2.forEach(System.out::println);
}
}
问题:我想将给出正确结果的for循环转换为stream.我当前的流代码给出了正确大小的结果,即(listOfMap*stringList),但由于浅拷贝,新键的值被覆盖.
电流输出
Expected Result using for loops
{1=a, 2=b, 3=c, 4=x}
{1=a, 2=b, 3=c, 4=y}
{1=a, 2=b, 3=c, 4=z}
{1=d, 2=e, 3=f, 4=x}
{1=d, 2=e, 3=f, 4=y}
{1=d, 2=e, 3=f, 4=z}
Result using streams
{1=a, 2=b, 3=c, 4=z}
{1=d, 2=e, 3=f, 4=z}
{1=a, 2=b, 3=c, 4=z}
{1=d, 2=e, 3=f, 4=z}
{1=a, 2=b, 3=c, 4=z}
{1=d, 2=e, 3=f, 4=z}
谢谢你的帮助.