首页 > 解决方案 > 如何像其他方法一样配置 intellij java formatter 来格式化 .stream()

问题描述

我正在尝试将 IntelliJ 格式化程序设置为对流使用与其他方法调用相同的新行格式。

如果我得到的代码行超过 100 个字符的限制,IntelliJ 会像这样格式化它:

StringBuilder stringBuilder = new StringBuilder();
stringBuilder
    .append("foo")
    .append("foo")
    .append("foo")
    .append("foo")
    .append("foo")
    .append("foo")
    .append("foo")
    .append("foo");

如果我有一行代码包含超过 100 个字符的限制的流,intellij 在流语句之后开始一个新行:

List<Integer> list = new ArrayList<>();
list.subList(0, 2).stream()
    .filter(foo -> foo.equals(foo))
    .filter(foo -> foo.equals(foo))
    .filter(foo -> foo.equals(foo));

如何告诉格式化程序像其他方法一样对流具有相同的格式?

List<Integer> list = new ArrayList<>();
list
    .subList(0, 2)
    .stream()
    .filter(foo -> foo.equals(foo))
    .filter(foo -> foo.equals(foo))
    .filter(foo -> foo.equals(foo));

此格式仅适用于代码行超过 100 个字符的限制,否则应保留在一行中。

编辑:我将我的 intellij 版本更新为 2019.2 并重新导入了我的 CodeStyle xml。现在我不能再重现我的问题了。

标签: javaintellij-idea

解决方案


我无法重现 IntelliJ IDEA Ultimate 2019.2 的问题。我创建了以下类:

public class Foo {

    void bar() {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("foo").append("foo").append("foo").append("foo").append("foo").append("foo").append("foo").append("foo");

        List<Integer> list = new ArrayList<>();
        list.subList(0, 2).stream().filter(foo -> foo.equals(foo)).filter(foo -> foo.equals(foo)).filter(foo -> foo.equals(foo));
    }

}

重新格式化 (CTRL+ALT+L) 后,代码如下所示:

public class Foo {

    void bar() {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder
                .append("foo")
                .append("foo")
                .append("foo")
                .append("foo")
                .append("foo")
                .append("foo")
                .append("foo")
                .append("foo");

        List<Integer> list = new ArrayList<>();
        list
                .subList(0, 2)
                .stream()
                .filter(foo -> foo.equals(foo))
                .filter(foo -> foo.equals(foo))
                .filter(foo -> foo.equals(foo));
    }

}

这是我作为 XML 的代码样式设置:

<code_scheme name="Project" version="173">
  <codeStyleSettings language="JAVA">
    <option name="ALIGN_MULTILINE_CHAINED_METHODS" value="true" />
    <option name="ALIGN_MULTILINE_PARAMETERS_IN_CALLS" value="true" />
    <option name="METHOD_PARAMETERS_WRAP" value="2" />
    <option name="THROWS_LIST_WRAP" value="1" />
    <option name="METHOD_CALL_CHAIN_WRAP" value="2" />
    <option name="WRAP_FIRST_METHOD_IN_CALL_CHAIN" value="true" />
    <option name="BINARY_OPERATION_WRAP" value="1" />
    <option name="ARRAY_INITIALIZER_WRAP" value="1" />
  </codeStyleSettings>
</code_scheme>

推荐阅读