如何为方法返回的流启用“类型信息”?

Gho*_*ica 9 java intellij-idea java-8 java-stream

由于有几个版本,IntelliJ具有一个非常有用的功能:将stream()语句的各个方法调用放在单独的行上时,IntelliJ在每行上都放置类型信息:

带有类型信息

但是,当您不stream()直接调用(例如从另一个方法返回)时,该信息将被省略:

没有类型

有没有办法说服IntelliJ在这种情况下显示此类信息?

作为纯文本,可以使用手动插入的注释来“显示”纯文本的问题:

public Stream<Entry<String, String>> withTypeInformation() {
    return generateMap() // Map<String, String>
            .entrySet()  // Set<Entry<String, String>>
            .stream()    // Stream<Set<Entry<String, String>>>
            .filter(e -> !e.getKey().equals("foo")) // Stream<Set<Entry<String, String>>>
            .filter(e -> !e.getKey().equals("bar")) // Stream<Set<Entry<String, String>>>
            .filter(e -> !e.getKey().equals("now"));
}

public Stream<Entry<String, String>> withoutTypeInformation() {
    return withTypeInformation() // no such info 
            .filter(e -> !e.getKey().equals("foo")) // not here either
            .filter(e -> !e.getKey().equals("bar")) // guess what, nothing, too
            .filter(e -> !e.getKey().equals("now"));
}
Run Code Online (Sandbox Code Playgroud)

请注意:第一种方法使用了生成器方法,该方法返回地图实例。IntelliJ足够聪明,可以给我类型信息吗?

小智 7

实际上,有一种启发式方法,使 IDEA 不显示此提示。如果单链不同类型的数量小于3,则不会显示。当表达式的类型很明显(例如构建器)时,需要避免垃圾邮件提示。

在 IntelliJ IDEA 2019.2 中计数不同类型,需要显示提示可以在设置中调整(如果设置为 1,提示将始终显示)。

注意:要获得该设置,必须转到 Preferences -> Editor -> Inlay Hints -> Java 并更改“方法提示”的“唯一类型计数”。