java - 递归函数中的类型安全未知返回类型?
问题描述
我有一种递归方法来展平嵌套地图,在Stream
. 它返回对象,因为我事先不知道嵌套的深度:
static Stream<Object> nestedMapFlattener(Object o) {
if (o instanceof Map<?, ?>) {
return
((Map<?, ?>) o)
.entrySet()
.stream()
.flatMap(entry ->
nestedMapFlattener(entry.getValue())
.map(entryOrSingle -> new AbstractMap.SimpleEntry<>(entry.getKey(), entryOrSingle))
)
;
}
return Stream.of(o);
}
要使用它,我在流中进行转换,当然会收到未经检查的警告:
@Test
public void nestedMapFlattenerTest() {
Map<Integer, Map<Integer, Map<Integer, Integer>>> threeFoldNestMap = new HashMap<Integer, Map<Integer, Map<Integer, Integer>>>() {{
put(
1,
new HashMap<Integer, Map<Integer, Integer>>() {{
put(
11,
new HashMap<Integer, Integer>() {{
put(111, 1110);
put(112, 1120);
}}
);
put(
12,
new HashMap<Integer, Integer>() {{
put(121, 1210);
put(122, 1220);
}}
);
}}
);
put(
2,
new HashMap<Integer, Map<Integer, Integer>>() {{
put(
21,
new HashMap<Integer, Integer>() {{
put(211, 2110);
put(212, 2120);
}}
);
put(
22,
new HashMap<Integer, Integer>() {{
put(221, 2210);
put(222, 2220);
}}
);
}}
);
put(
3,
new HashMap<Integer, Map<Integer, Integer>>() {{
put(
31,
new HashMap<Integer, Integer>() {{
put(311, 3110);
put(312, 3120);
}}
);
put(
32,
new HashMap<Integer, Integer>() {{
put(321, 3210);
put(322, 3220);
}}
);
}}
);
}};
nestedMapFlattener(threeFoldNestMap)
.map(o -> (Map.Entry<Integer, Map.Entry<Integer, Map.Entry<Integer, Integer>>>) o)
.map(o -> "" + o.getKey() + " " + o.getValue().getKey() + " " + o.getValue().getValue().getKey() + " " + o.getValue().getValue().getValue())
.forEach(System.out::println);
//prints:
//1 11 112 1120
//1 11 111 1110
//1 12 121 1210
//1 12 122 1220
//2 21 211 2110
//2 21 212 2120
//2 22 221 2210
//2 22 222 2220
//3 32 321 3210
//3 32 322 3220
//3 31 311 3110
//3 31 312 3120
}
我想知道,是否有更好的方法来做到这一点,因为我认为它有点滥用类型安全的概念?