Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to convert the List of Objects to the Map<String, Integer> where the second value (Integer) of Map will be generating by auto?

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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()));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading