-3

I am using java 8 stream features now i want to store string value in local variable,but its showing local variables referenced from a lambda expression must be final or effectively final.I also tried final keyword its getting same.I need clarification its possible or not.

public static void main(String[] args) {
        List list = Arrays.asList("java", "stream", "scala");
        String data = "";
        list.forEach(action -> {
            data = action.toString();
            System.out.println("data :" + data);
        });
    } 
8
  • 1
    You need data outside lambda? it seems you can remove the variable Commented Dec 24, 2019 at 7:18
  • Even if it was possible, what's the point? you overwrite the value of data with each element of the List, so it would have the last element in the end. Do you wish to concatenate all these Strings? If you do, there are other ways to achieve this. Commented Dec 24, 2019 at 7:18
  • yes i need outside lambda.whatever i stored in list. For ex : data=java Commented Dec 24, 2019 at 7:20
  • Show what you do with data outside lambda Commented Dec 24, 2019 at 7:21
  • 1
    what do you want to do with that variable ? @AjithDeivam and why Commented Dec 24, 2019 at 7:32

2 Answers 2

0

If you will try to reinitialize final variable, It will throw error.

I suggest you to use arraylist/list/array as final and add value to list , example as below

final ArrayList<String> strings = new ArrayList<>();
        List list = Arrays.asList("java", "stream", "scala");
        list.forEach(action -> {
            strings.add(action.toString());

        });
Sign up to request clarification or add additional context in comments.

Comments

0
List<String> list = Arrays.asList("java", "stream", "scala");
StringBuilder data = new StringBuilder();
list.forEach(action -> {
    data.replace(0, data.length(), action);
    System.out.println("data :" + data);
});


Although I **don't** recommend it.


Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.