I have List<City> cities
. I need to convert cities
into a map Map<String, Integer>
, where the value (Integer
) has to be auto-generated.
I tried this, but it seems not allowed to use counter
like that because of atomic error. Ho to solve this task?
public Map<String, Integer> convertListToMap(List<City> cities) {
Integer counter=0;
return cities.stream().forEach(elem->tollFreeVehicles.put(elem.getName(), counter ));
}
CodePudding user response:
Local variables that are allowed to be used in the lambda expressions needs to be final or effectively final.
Have a look at the Oracle's tutorial on lambdas. A short excerpt:
a lambda expression can only access local variables and parameters of the enclosing block that are final or effectively final. In this example, the variable z is effectively final; its value is never changed after it's initialized.
You can construct a map from a list using indices of items in the list as values by utilizing IntStream.range()
.
Also note that forEach()
doesn't return a value. In order to generate a map as a result of the execution of the stream pipeline that will be returned from the method, you need to use collect()
as terminal operation.
Map<String, Integer> result =
IntStream.range(0, cities.size())
.boxed()
.collect(Collectors.toMap(i -> cities.get(i).getName(),
Function.identity()));