I have List<City> cities. I need to convert cities to Map<String, Integer> where the second value (Integer) of Map will be generating by auto.
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++));
}
>Solution :
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():
Map<String, Integer> result =
IntStream.range(0, cities.size()).stream()
.boxed()
.collect(Collectors.toMap(i -> cities.get(i).getName(),
Function.identity()));