prosource

Java 8: 새 줄과 들여쓰기로 람다 서식 지정

probook 2023. 4. 28. 21:08
반응형

Java 8: 새 줄과 들여쓰기로 람다 서식 지정

람다 들여쓰기를 통해 달성하고자 하는 것은 다음과 같습니다.

다중 행 문:

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

한 줄 문:

List<String> strings = Arrays.stream(ppl)
                         .map((x) -> x.toUpperCase())
                         .filter((x) -> x.contains("(M)"))
                         .collect(Collectors.toList());



현재 이클립스는 다음으로 자동 포맷됩니다.

다중 행 문:

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

한 줄 문:

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

그리고 나는 이것이 정말 지저분하다는 것을 발견했다, 어떻게 그것이.collect은 통는바아있습다니 바로 .return그리고 그 사이에는 공간이 전혀 없습니다.람다를 들여쓰기된 새 라인에서 시작할 수 있다면 더 좋습니다..filter(는 통는바위있것입다니을 입니다..collect(call. 표준 할 수 부분에 이지만, 니다합호에 . 그러나 표준 Java-8 Eclipse Formatter로 사용자 지정할 수 있는 유일한 것은 람다 본체의 시작 부분에 있는 브레이스이지만,()사전에 괄호를 사용하거나 들여쓰기를 사용하지 않습니다.

그리고 단회선 통화의 경우, 기본적인 회선 랩을 사용하여 체인으로 된 엉망진창이 됩니다.나중에 암호 해독이 어려운 이유를 설명할 필요가 없을 것 같습니다.

이클립스에서 포맷을 더 사용자 지정하고 첫 번째 포맷 유형을 달성할 수 있는 방법이 있습니까? (또는 IntelliJ IDEA와 같은 다른 IDE에서 선택적으로)



파일: IntelliJ IDEA 13 Community Edition(인텔리제이 IDEA 13 커뮤니티 에디션P)으로, 다음과 같습니다(이 경우 8인 연속 들여쓰기로 정의됨).

public static void main(String[] args)
{
    int[] x = new int[] {1, 2, 3, 4, 5, 6, 7};
    int sum = Arrays.stream(x)
            .map((n) -> n * 5)
            .filter((n) -> {
                System.out.println("Filtering: " + n);
                return n % 3 != 0;
            })
            .reduce(0, Integer::sum);

    List<Integer> list = Arrays.stream(x)
            .filter((n) -> n % 2 == 0)
            .map((n) -> n * 4)
            .boxed()
            .collect(Collectors.toList());
    list.forEach(System.out::println);
    System.out.println(sum);    

또한 다음과 같이 체인 방식 호출을 "정렬"할 수 있습니다.

    int sum = Arrays.stream(x)
                    .map((n) -> n * 5)
                    .filter((n) -> {
                        System.out.println("Filtering: " + n);
                        return n % 3 != 0;
                    })
                    .reduce(0, Integer::sum);


    List<Integer> list = Arrays.stream(x)
                               .filter((n) -> n % 2 == 0)
                               .map((n) -> n * 4)
                               .boxed()
                               .collect(Collectors.toList());
    list.forEach(System.out::println);
    System.out.println(sum);
}

저는 개인적으로 그것이 더 말이 되지만, 두 번째 버전은 그것을 너무 멀리 밀어내기 때문에 첫 번째 버전을 선호합니다.

첫 번째 설정을 담당하는 설정은 다음과 같습니다.

<?xml version="1.0" encoding="UTF-8"?>
<code_scheme name="Zhuinden">
  <option name="JD_ALIGN_PARAM_COMMENTS" value="false" />
  <option name="JD_ALIGN_EXCEPTION_COMMENTS" value="false" />
  <option name="JD_ADD_BLANK_AFTER_PARM_COMMENTS" value="true" />
  <option name="JD_ADD_BLANK_AFTER_RETURN" value="true" />
  <option name="JD_P_AT_EMPTY_LINES" value="false" />
  <option name="JD_PARAM_DESCRIPTION_ON_NEW_LINE" value="true" />
  <option name="WRAP_COMMENTS" value="true" />
  <codeStyleSettings language="JAVA">
    <option name="KEEP_FIRST_COLUMN_COMMENT" value="false" />
    <option name="BRACE_STYLE" value="2" />
    <option name="CLASS_BRACE_STYLE" value="2" />
    <option name="METHOD_BRACE_STYLE" value="2" />
    <option name="ELSE_ON_NEW_LINE" value="true" />
    <option name="WHILE_ON_NEW_LINE" value="true" />
    <option name="CATCH_ON_NEW_LINE" value="true" />
    <option name="FINALLY_ON_NEW_LINE" value="true" />
    <option name="ALIGN_MULTILINE_PARAMETERS" value="false" />
    <option name="SPACE_WITHIN_BRACES" value="true" />
    <option name="SPACE_BEFORE_IF_PARENTHESES" value="false" />
    <option name="SPACE_BEFORE_WHILE_PARENTHESES" value="false" />
    <option name="SPACE_BEFORE_FOR_PARENTHESES" value="false" />
    <option name="SPACE_BEFORE_TRY_PARENTHESES" value="false" />
    <option name="SPACE_BEFORE_CATCH_PARENTHESES" value="false" />
    <option name="SPACE_BEFORE_SWITCH_PARENTHESES" value="false" />
    <option name="SPACE_BEFORE_SYNCHRONIZED_PARENTHESES" value="false" />
    <option name="SPACE_BEFORE_ARRAY_INITIALIZER_LBRACE" value="true" />
    <option name="METHOD_PARAMETERS_WRAP" value="1" />
    <option name="EXTENDS_LIST_WRAP" value="1" />
    <option name="THROWS_LIST_WRAP" value="1" />
    <option name="EXTENDS_KEYWORD_WRAP" value="1" />
    <option name="THROWS_KEYWORD_WRAP" value="1" />
    <option name="METHOD_CALL_CHAIN_WRAP" value="2" />
    <option name="BINARY_OPERATION_WRAP" value="1" />
    <option name="BINARY_OPERATION_SIGN_ON_NEXT_LINE" value="true" />
    <option name="ASSIGNMENT_WRAP" value="1" />
    <option name="IF_BRACE_FORCE" value="3" />
    <option name="DOWHILE_BRACE_FORCE" value="3" />
    <option name="WHILE_BRACE_FORCE" value="3" />
    <option name="FOR_BRACE_FORCE" value="3" />
    <option name="PARAMETER_ANNOTATION_WRAP" value="1" />
    <option name="VARIABLE_ANNOTATION_WRAP" value="1" />
    <option name="ENUM_CONSTANTS_WRAP" value="2" />
  </codeStyleSettings>
</code_scheme>

모든 것이 합리적인지 확인하려고 노력했지만, 제가 뭔가를 망쳤을 수도 있기 때문에 약간의 조정이 필요할 수도 있습니다.

만약 당신이 나와 같은 헝가리인이고 헝가리어 레이아웃을 사용한다면, 이 키맵은 당신에게 유용할 것입니다. 그래서 당신은 AltGR+F, AltGR+G, AltGR+B, AltGR+N 및 AltGR+M(Ctrl+Alt에 해당함)을 사용할 수 없게 됩니다.

<?xml version="1.0" encoding="UTF-8"?>
<keymap version="1" name="Default copy" parent="$default">
  <action id="ExtractMethod">
    <keyboard-shortcut first-keystroke="shift control M" />
  </action>
  <action id="GotoImplementation">
    <mouse-shortcut keystroke="control alt button1" />
  </action>
  <action id="GotoLine">
    <keyboard-shortcut first-keystroke="shift control G" />
  </action>
  <action id="Inline">
    <keyboard-shortcut first-keystroke="shift control O" />
  </action>
  <action id="IntroduceField">
    <keyboard-shortcut first-keystroke="shift control D" />
  </action>
  <action id="Mvc.RunTarget">
    <keyboard-shortcut first-keystroke="shift control P" />
  </action>
  <action id="StructuralSearchPlugin.StructuralReplaceAction" />
  <action id="Synchronize">
    <keyboard-shortcut first-keystroke="shift control Y" />
  </action>
</keymap>

IntelliJ는 람다의 시작 대괄호를 새 줄에 넣을 수 있는 방법을 제공하지 않는 것처럼 보이지만, 그렇지 않으면 상당히 합리적인 형식 지정 방법이므로 이를 수락된 것으로 표시하겠습니다.

이클립스에서 한 줄 문의 경우:

프로젝트 또는 글로벌 환경설정에서 다음으로 이동합니다.Java -> Code Style -> Formatter -> Edit -> Line Wrapping -> Function Calls -> Qualified Invocations,세트Wrap all elements, except first if not necessary체크 표시Force split, even if line shorter than maximum line width.

즉시 Intelli J13이 당신을 위해 일할 것입니다.

이런 식으로 쓴다면,

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

그런 다음 자동 포맷터를 적용합니다(변경 사항 없음).

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

한 줄 문에 대해서도 마찬가지입니다.저는 IntelliJ가 자동 포맷을 적용하는 방식에 더 유연하다는 것을 경험했습니다.IntelliJ는 줄 바꿈을 제거하거나 추가할 가능성이 낮으며, 줄 바꿈을 거기에 두면 줄 바꿈을 거기에 놓으려는 것으로 가정합니다.IntelliJ는 당신을 위해 기꺼이 당신의 탭 공간을 조정할 것입니다.


IntelliJ는 이 작업 중 일부를 수행하도록 구성할 수도 있습니다."설정" -> "코드 스타일" -> "자바"에서 "랩핑 및 브레이스" 탭에서 "체인 메소드 호출"을 "항상 랩핑"으로 설정할 수 있습니다.

자동 포맷 전

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

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

자동 포맷 후

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

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

이클립스(화성)에는 람다 식 포맷터에 대한 옵션이 있습니다.

에 가다Window > Preferences > Java > Code Style > Formatter

여기에 이미지 설명 입력

다음을 클릭합니다.Edit단추, 다음으로 이동Braces태그 지정 및 설정Lambda Body로.Next Line Indented

여기에 이미지 설명 입력

다른 옵션은 이러한 속성을 프로젝트 설정으로 업데이트하는 것입니다.(yourWorkspace > yourProject > .settings > org.eclipse.jdt.core.prefs)

org.eclipse.jdt.core.formatter.insert_space_before_lambda_arrow=insert
org.eclipse.jdt.core.formatter.brace_position_for_lambda_body=next_line_shifted

이 질문은 이제 오래되었으며 안타깝게도 Eclipse 포맷터의 기본 구성은 여전히 읽기 쉬운 방식으로 기능 코드를 작성하기에 사용자에게 친숙하지 않습니다.

저는 다른 모든 답변에 언급된 모든 것을 시도했지만 대부분의 사용 사례에 적합한 사람은 아무도 없습니다.
어떤 사람들에게는 괜찮지만 다른 사람들에게는 불쾌할 수 있습니다.

저는 대부분의 시간 동안 저에게 맞는 방법을 찾았습니다.
다른 사람들에게 도움이 될 수 있다는 생각으로 공유합니다.

제 방식에는 트레이드오프가 있습니다. 즉, 적격한 각 호출은 항상 별개의 라인에 있어야 한다는 것을 인정하는 것입니다.
포메터 구성에서 누락된 옵션일 수 있습니다. 를 사용하는 대신 줄을 감쌀 호출의 관점에서 임계값을 나타냅니다.1부전승으로 호출합니다.

다음은 이를 올바르게 처리하기 위한 두 가지 결합된 도구입니다.

  • 대부분의 경우에 대해 Eclipse 포맷터 구성 사용자 정의

  • 다음을 사용하여 코드 템플릿 만들기//@formatter:off ... //@formatter:on구석진 곳에


Eclipse 포맷터 구성 사용자 정의
변경할 값은 캡처에서 빨간색으로 둘러싸여 있습니다.

1단계) 고유의 Java 코드 스타일 포맷터 만들기

Preferences메뉴와 트리에서, 로 이동합니다.Java -> Code Style -> Formatter.
새 항목을 만들려면 "새 항목"을 클릭하십시오.Profile("Java 규약"으로 초기화).

이클립스 포맷터

다음 두 단계는 사용자 지정 포맷터 프로필에서 수행해야 합니다.

줄 바꿈 라인의 )

식별 구성

수정을 통해 표 대신 공백을 사용할 수 있습니다.
열 들여쓰기 옵션으로 줄 바꿈 정책을 구성하기 때문에 다음 단계에서 중요합니다.
그것은 정말로 불쾌한 공간을 만들지 않을 것입니다.

들여쓰기 및 정책 변경3단계)

줄 바꿈선 크기


다음은 문제 코드가 포함된 테스트 형식입니다.

을 지정하기전에 : " " "

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

void singleLineStatements() {
    String[] ppl = new String[] { "Karen (F)", "Kevin (M)", "Lee (M)", "Joan (F)", "Des(M)", "Rick (M)" };
    List<String> strings = Arrays.stream(ppl).map((x) -> x.toUpperCase())
            .filter((x) -> x.contains("(M)")).collect(Collectors.toList());
    strings.stream().forEach(System.out::println);
}

지정후: 맷후 포:

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

void singleLineStatements() {
    String[] ppl = new String[] { "Karen (F)", "Kevin (M)", "Lee (M)", "Joan (F)", "Des(M)", "Rick (M)" };
    List<String> strings = Arrays.stream(ppl)
                                 .map((x) -> x.toUpperCase())
                                 .filter((x) -> x.contains("(M)"))
                                 .collect(Collectors.toList());
    strings.stream()
           .forEach(System.out::println);
}

로 템플릿 //@formatter:off ... //@formatter:on구석진 곳에

으로 쓰기 붙여넣기하기//@formatter:on그리고.//@formatter:off당신이 거의 쓰지 않기 때문에 괜찮습니다.
하지만 만약 여러분이 그것을 매주 몇 번씩 써야 하거나 심지어 하루가 다르게 써야 한다면, 더 자동적인 방법은 환영받을 것입니다.

1) Editor template 1(으)로 이동합니다.

Preferences메뉴와 트리에서, 로 이동합니다.Java ->Editor -> Template.
여기에 이미지 설명 입력

2단계) 선택한 코드에 대한 서식을 사용하지 않도록 템플릿 만들기

템플릿 포맷터 끄기

이제 테스트할 수 있습니다.
서식을 사용하지 않을 줄을 선택합니다.
이제입을 입력합니다.ctrl+space두 번(첫 번째는 "자바 제안"이고 두 번째는 "템플릿 제안").
은 다음과 같은.

견본 제안

다음을 선택합니다.fmt템플릿을 스크린샷과 같이 입력하고 "Enter"를 클릭합니다.알았어!

템플릿 적용 후 결과

함수 뒤에 빈 주석 "//"을 추가하여 한 줄 문 형식을 지정합니다.

List<Integer> list = Arrays.stream(x) //
                           .filter((n) -> n % 2 == 0) //
                           .map((n) -> n * 4) //
                           .boxed() //
                           .collect(Collectors.toList());

이상적이지는 않지만 밀도가 약간 높은 부분에 대해서만 포맷터를 끌 수 있습니다.예를들면

  //@formatter:off
  int sum = Arrays.stream(x)
        .map((n) -> n * 5)
        .filter((n) -> {
            System.out.println("Filtering: " + n);
            return n % 3 != 0;
        })
        .reduce(0, Integer::sum);
  //@formatter:on

"Windows > 환경설정 > Java > Code Style > Formatter"로 이동합니다.편집을 클릭합니다.단추를 클릭하고 "태그 끄기/켜기" 탭으로 이동하여 태그를 활성화합니다.

나에게 효과가 있었던 옵션은 똑딱거리는 것이었습니다.Never join already wrapped lines[환경설정]에서 [환경설정]에서 [형식]의 [라인 래핑] 섹션에 있습니다.

사용자 지정 Eclipse 포맷터가 아직 없는 경우:

Eclipse 기본 설정 Java > Code Style > Formatter 새 이름 입력 클릭 컨트롤 줄 바꿈

종단 줄 바꿈 탭 편집 "이미 묶은 줄에 가입 안 함" 선택

결국 이렇게 될 것입니다.

    String phrase = employeeList
            .stream()
            .filter(p -> p.getAge() >= 33)
            .map(p -> p.getFirstName())
            .collect(Collectors.joining(" and ", "In Germany ", " are of legal age."));

다음 줄에 every.start를 입력해야 합니다.

크레딧 - https://www.selikoff.net/2017/07/02/eclipse-and-line-wrapping/

언급URL : https://stackoverflow.com/questions/24649971/java-8-formatting-lambda-with-newlines-and-indentation

반응형