无法引用Java 8 Stream非静态方法流

时间:2018-01-27 12:39:53

标签: java

我在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

我该如何解决?

1 个答案:

答案 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());
}