我在IDEA中遇到了流问题。 我有一个简单的测试:
@Test
public void shouldFlattenAListOfList() throws Exception {
List<String> flatten = PTestImpl.flatten(
asList("a", asList("b", asList("c", "d")), "e"));
assertThat(flatten, hasSize(5));
assertThat(flatten, hasItems("a", "b", "c", "d", "e"));
}
静态方法
public static <T> List<T> flatten(List<?> list){
return list.stream()
.flatMap(Collection::stream)
.collect(Collectors.toList());;
}
但IDEA告诉我:
Error:(44, 26) java: invalid method reference
non-static method stream() cannot be referenced from a static context
我该如何解决?
答案 0 :(得分:2)
如果您不想对接收列表中元素的类型做出任何假设,则必须更改flatten
方法体及其返回类型:
public static List<?> flatten(List<?> list){
return list.stream()
.flatMap(e -> e instanceof List ? flatten((List) e).stream() : Stream.of(e))
.collect(Collectors.toList());
}