Supplier<List<String>>
is a function that gets invoked whenever the get
method is run.
In your case, str
is similar to the following lambda expression:
Supplier<List<String>> str = () -> new ArrayList<>();
Which means that every time str.get()
is called, the function gets called, and the body new ArrayList<>()
is executed, thus resulting in a new list every time.
If you want the Supplier
to always return the same list, then you need to capture it:
List<String> list = new ArrayList<>();
Supplier<List<String>> str = () -> list;
This way, every time str.get()
runs, it will just return the same list it captured. But, IMO, this doesn't seem like good practice, it would seem rather correct to just keep a reference to the variable instead of keeping it behind a Supplier (which implies a function producing a value).