Java 8: Formatting lambda with newlines and indentation

后端 未结 9 1147
[愿得一人]
[愿得一人] 2020-12-12 23:46

What I would like to achieve with lambda indentation is the following:

Multi-line statement:

String[] ppl = new String[] { \"Karen (F)\", \"Kevin (M)         


        
9条回答
  •  情歌与酒
    2020-12-13 00:02

    Out of the box IntelliJ 13 will probably work for you.

    If I write it this way:

    // Mulit-Line Statement
    String[] ppl = new String[] { "Karen (F)", "Kevin (M)", "Lee (M)", "Joan (F)", "Des (M)", "Rick (M)" };
    List strings = Arrays.stream(ppl)
            .filter(
                    (x) ->
                    {
                        return x.contains("(M)");
                    }
            ).collect(Collectors.toList());
    strings.stream().forEach(System.out::println);
    

    And then apply the auto formatter (no changes):

    // Mulit-Line Statement
    String[] ppl = new String[]{"Karen (F)", "Kevin (M)", "Lee (M)", "Joan (F)", "Des (M)", "Rick (M)"};
    List strings = Arrays.stream(ppl)
            .filter(
                    (x) ->
                    {
                        return x.contains("(M)");
                    }
            ).collect(Collectors.toList());
    strings.stream().forEach(System.out::println);
    

    The same is true for your single line statement. It has been my experience that IntelliJ is more flexible in how its auto formatting is applied. IntelliJ is less likely to remove or add line returns, if you put it there then it assumes you meant to put it there. IntelliJ will happily adjust your tab-space for you.


    IntelliJ can also be configured to do some of this for you. Under "settings" -> "code style" -> "java", in the "Wrapping and Braces" tab you can set "chain method calls" to "wrap always".

    Before Auto-Formatting

    // Mulit-Line Statement
    List strings = Arrays.stream(ppl).filter((x) -> { return x.contains("(M)"); }).collect(Collectors.toList());
    
    // Single-Line Statement
    List strings = Arrays.stream(ppl).map((x) -> x.toUpperCase()).filter((x) -> x.contains("(M)")).collect(Collectors.toList());
    

    After Auto-Formatting

    // Mulit-Line Statement
    List strings = Arrays.stream(ppl)
            .filter((x) -> {
                return x.contains("(M)");
            })
            .collect(Collectors.toList());
    
    // Single-Line Statement
    List strings = Arrays.stream(ppl)
            .map((x) -> x.toUpperCase())
            .filter((x) -> x.contains("(M)"))
            .collect(Collectors.toList());
    

提交回复
热议问题