无法引用Java 8 Stream非静态方法流 [英] Java 8 Stream non static method stream cannot be referenced

查看:176
本文介绍了无法引用Java 8 Stream非静态方法流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在IDEA中遇到流问题. 我有一个简单的测试:

I have problem with streams in IDEA. I have a simple test:

 @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

我该如何解决?

推荐答案

如果您不想对接收到的元素的类型做任何假设,则必须更改flatten方法主体及其返回类型.列表:

The flatten method body and its return type has to be changed, if you do not want to make any assumptions about the type of the elements in the received list:

public static List<?> flatten(List<?> list){
    return list.stream()
        .flatMap(e -> e instanceof List ? flatten((List) e).stream() : Stream.of(e))
        .collect(Collectors.toList());
}

这篇关于无法引用Java 8 Stream非静态方法流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆