如何将对象列表转换为具有自动生成值的 Map<String, Integer>?

How to convert a List of objects into a Map<String, Integer> with auto-generated values?

我有List<City> cities。我需要将 cities 转换为映射 Map<String, Integer>,其中必须自动生成值 (Integer)。

我试过了,但由于原子错误,似乎不允许这样使用 counter。何解决这个任务?

public Map<String, Integer> convertListToMap(List<City> cities) {
    Integer counter=0;
    return cities.stream().forEach(elem->tollFreeVehicles.put(elem.getName(), counter++));
}

允许在 lambda 表达式中使用的局部变量需要是 final最终有效.

看看Oracle's tutorial on lambdas。简短摘录:

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.

您可以使用 list 中的项目索引从 list 构建 map作为 values 通过利用 IntStream.range().

另请注意 forEach() 不是 return 值。为了生成 map 作为将从方法 return 编辑的流管道的执行结果,您需要使用 collect() 作为终端操作。

Map<String, Integer> result = 
    IntStream.range(0, cities.size())
             .boxed()
             .collect(Collectors.toMap(i -> cities.get(i).getName(),
                                       Function.identity()));