如何将 Java 以下的 for 循环转换为流?
How convert below Java for loop to stream?
我一直在尝试使用 map()
来执行前两个步骤,但我不太确定如何获取表示当前迭代计数的索引 i:
for (int i = 0; i < carList.size(); i++) {
String country = carList.get(i).getCountry();
List<Integer> indexes = carsToIndexMap.getOrDefault(country, new ArrayList<>());
indexes.add(i);
carsToIndexMap.put(country, indexes);
}
我一直在尝试这样的事情:
carList.stream()
.map(p -> p.getCountry())
.map(country -> carsToIndexMap.getOrDefault(country, new ArrayList<>()))
如果我没记错的话,您似乎在寻找按 country
和 indexes
对应处理的汽车的分组。这可以通过使用具有 carList
大小范围和 groupingBy
收集器的 IntStream
来实现。
Map<String, List<Integer>> carsToIndexMap = IntStream.range(0, carList.size())
.boxed()
.collect(Collectors.groupingBy(i -> carList.get(i).getCountry()));
建议:你的变量名应该表明key是country而不是cars,比如countryIndices
.
我一直在尝试使用 map()
来执行前两个步骤,但我不太确定如何获取表示当前迭代计数的索引 i:
for (int i = 0; i < carList.size(); i++) {
String country = carList.get(i).getCountry();
List<Integer> indexes = carsToIndexMap.getOrDefault(country, new ArrayList<>());
indexes.add(i);
carsToIndexMap.put(country, indexes);
}
我一直在尝试这样的事情:
carList.stream()
.map(p -> p.getCountry())
.map(country -> carsToIndexMap.getOrDefault(country, new ArrayList<>()))
如果我没记错的话,您似乎在寻找按 country
和 indexes
对应处理的汽车的分组。这可以通过使用具有 carList
大小范围和 groupingBy
收集器的 IntStream
来实现。
Map<String, List<Integer>> carsToIndexMap = IntStream.range(0, carList.size())
.boxed()
.collect(Collectors.groupingBy(i -> carList.get(i).getCountry()));
建议:你的变量名应该表明key是country而不是cars,比如countryIndices
.