-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);
        });
    } 
Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Ajith Deivam
  • 736
  • 4
  • 11
  • 27
  • 1
    You need `data` outside lambda? it seems you can remove the variable – Ori Marko Dec 24 '19 at 07: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 `String`s? If you do, there are other ways to achieve this. – Eran Dec 24 '19 at 07:18
  • yes i need outside lambda.whatever i stored in list. For ex : data=java – Ajith Deivam Dec 24 '19 at 07:20
  • Show what you do with `data` outside lambda – Ori Marko Dec 24 '19 at 07:21
  • Does this answer your question? [Java - changing the value of a final variable from within a lambda](https://stackoverflow.com/questions/31851892/java-changing-the-value-of-a-final-variable-from-within-a-lambda) – Syed Mehtab Hassan Dec 24 '19 at 07:21
  • Why would you wanna store it if you are going to overwrite it anyway? Wouldn't it always be the case in this List iteration you are going to end up with data as ``` "scala" ```? What are you doing to do by storing this anyway? – papaya Dec 24 '19 at 07:23
  • @ Siddarth Sreeni I need only store any values from list outside lambda. – Ajith Deivam Dec 24 '19 at 07:26
  • 1
    what do you want to do with that variable ? @AjithDeivam and why – Ryuzaki L Dec 24 '19 at 07:32

2 Answers2

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.


Vishwa Ratna
  • 5,567
  • 5
  • 33
  • 55
krun
  • 19
  • 3
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());

        });
LostGeek
  • 123
  • 13