[Error] Variable used in lambda expression should be final or effectively final

박채은·2022년 11월 11일
0

Error

목록 보기
1/4

문제

  • 인자로 공백이 없는 문자열을 받음
  • 문자열에 존재하는 문자를 key, 해당 문자가 등장하는 횟수를 value로 하여 HashMap에 저장한다.

푸는 방법은 다양하겠지만, Stream을 사용해서 풀어봤다.


import java.util.*;

public class Solution { 
  public HashMap<Character, Integer> countAllCharacter(String str) {
    HashMap<Character, Integer> hashMap = new HashMap<Character, Integer>();
    if(str.length()==0) return null;

    for(int i=0;i<str.length();i++){
      hashMap.put(str.charAt(i), str.chars().filter(c-> c == str.charAt(i)).count());
    }
    return hashMap;
  }
}

Variable used in lambda expression should be final or effectively final 에러가 발생하였다.

lambda 안에서는 final 변수, effectively final 변수만 사용 가능하다는 뜻이다.

effectively final

https://codechacha.com/ko/java-effectively-final-vs-final/

final이 붙지 않았지만, 값이 변하지 않는 변수를 Effectively final 변수라고 한다.
해당 변수가 변하는 순간, Effectively final 변수가 아니게 된다.

왜 lambda는 final/Effectively final 변수만 접근할 수 있을까?

https://cobbybb.tistory.com/19
https://ecsimsw.tistory.com/794


해결

import java.util.*;

public class Solution { 
  public HashMap<Character, Integer> countAllCharacter(String str) {
    HashMap<Character, Integer> hashMap = new HashMap<Character, Integer>();
    if(str.length()==0) return null;

    for(int i=0;i<str.length();i++){
      char findChar = str.charAt(i);
      hashMap.put(findChar, (int) str.chars().filter(c-> c == findChar).count());
    }
    return hashMap;
  }
}
  • 람다 내부의 str.charAt(i)findChar 변수로 바꿔준다.
  • findChar 변수는 매번 for문을 돌 때마다, 다시 선언되고 변수는 바뀌지 않기 때문에 Effectively final 변수가 된다.

0개의 댓글